In [ ]:
# 起手式
import numpy as np
In [ ]:
np.array([1,2,3,4])
In [ ]:
x = _
In [ ]:
y = np.array([[1.,2,3],[4,5,6]])
y
看 ndarray 的第一件事情: shape , dtype
In [ ]:
x.shape
In [ ]:
y.shape
In [ ]:
x.dtype
In [ ]:
y.dtype
In [ ]:
# import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
# 畫圖
plt.plot(x, 'x');
In [ ]:
# 建立 0 array
np.zeros_like(y)
In [ ]:
np.zeros((10,10))
In [ ]:
# 跟 range 差不多
x = np.arange(0, 10, 0.1)
# 亂數
y = np.random.uniform(-1,1, size=x.shape)
plt.plot(x, y)
這是一堆資料
最簡單的計算是 逐項計算
see also np.vectorize
In [ ]:
x = np.linspace(0, 2* np.pi, 1000)
plt.plot(x, np.sin(x))
In [ ]:
#可以用 %run -i 跑參考範例
%run -i q0.py
In [ ]:
# 或者看看參考範例
#%load q0.py
In [ ]:
# 參考答案
#%load q1.py
In [ ]:
a = np.arange(30)
a
In [ ]:
a[5]
In [ ]:
a[3:7]
In [ ]:
# 列出所有奇數項
a[1::2]
In [ ]:
# 還可以用來設定值
a[1::2] = -1
a
In [ ]:
# 或是
a[1::2] = -a[::2]-1
a
In [ ]:
%run -i q2.py
#%load q2.py
In [ ]:
b = np.array([[1,2,3], [4,5,6], [7,8,9]])
b
In [ ]:
b[1][2]
In [ ]:
b[1,2]
In [ ]:
b[1]
In [ ]:
b = np.random.randint(0,99, size=(5,10))
b
試試看下面的結果
想一下是怎麼一回事(numpy 在想什麼?)
In [ ]:
b[[1,3]]
In [ ]:
b[(1,3)]
In [ ]:
b[[1,2], [3,4]]
In [ ]:
b[[(1,2),(3,4)]]
In [ ]:
b[[True, False, False, True, False]]
In [ ]:
#參考範例
%run -i q4.py
In [ ]:
# 還記得剛才的
from PIL import Image
img = Image.open('img/Green-Rolling-Hills-Landscape-800px.png')
img_array = np.array(img)
Image.fromarray(img_array)
In [ ]:
# 用來顯示圖片的函數
from IPython.display import display
def show(img_array):
display(Image.fromarray(img_array))
In [ ]:
# 將圖片縮小成一半
%run -i q_half.py
In [ ]:
# 將圖片放大
%run -i q_scale2.py
In [ ]:
# 圖片上下顛倒
show(img_array[::-1])
In [ ]:
%run -i q_paste.py
In [ ]:
%run -i q_grayscale.py
In [ ]:
# 用迴圈畫圓
%run -i q_slow_circle.py
In [ ]:
# 用 fancy index 畫圓
%run -i q_fast_circle.py
In [ ]:
# 還可以做模糊化
a = img_array.astype(float)
for i in range(10):
a[1:,1:] = (a[1:,1:]+a[:-1,1:]+a[1:,:-1]+a[:-1,:-1])/4
show(a.astype('uint8'))
In [ ]:
# 求邊界
a = img_array.astype(float)
a = a @ [0.299, 0.587, 0.114, 0]
a = np.abs((a[1:]-a[:-1]))*2
show(a.astype('uint8'))
In [ ]:
# reshaping 的應用
R,G,B,A = img_array.reshape(-1,4).T
plt.hist((R,G,B,A), color="rgby");
In [ ]:
# 例子
show(np.hstack([img_array, img_array2]))
In [ ]:
# 例子
np.concatenate([img_array, img_array2], axis=2).shape
In [ ]:
np.max([1,2,3,4])
In [ ]:
np.sum([1,2,3,4])
In [ ]:
np.mean([1,2,3,4])
In [ ]:
np.min([1,2,3,4])
多重意義的運用, 水平平均,整合垂直平均
In [ ]:
x_mean = img_array.astype(float).min(axis=0, keepdims=True)
print(x_mean.dtype, x_mean.shape)
y_mean = img_array.astype(float).min(axis=1, keepdims=True)
print(y_mean.dtype, y_mean.shape)
# 自動 broadcast
xy_combined = ((x_mean+y_mean)/2).astype('uint8')
show(xy_combined)
先從點積開始
In [ ]:
# = 1*4 + 2*5 + 4*6
np.dot([1,2,3], [4,5,6])
In [ ]:
u=np.array([1,2,3])
v=np.array([4,5,6])
print( u@v )
print( (u*v).sum() )
如果忘記矩陣乘法是什麼了, 參考這裡 http://matrixmultiplication.xyz/ 或者 http://eli.thegreenplace.net/2015/visualizing-matrix-multiplication-as-a-linear-combination/
矩陣乘法可以看成是:
np.sum(a[:,:, np.newaxis] * b[np.newaxis, : , :], axis=1)
dot(a, b)[i,k] = sum(a[i,:] * b[:, k])
要如何推廣?
tensordot, tensor contraction, a.shape=(3,4,5), b.shape=(4,5,6), axis = 2 時等價於
np.sum(a[..., np.newaxis] * b[np.newaxis, ...], axis=(1, 2))
tensordot(a,b)[i,k]=sum(a[i, ...]* b[..., k])
dot
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
np.tensordot(a,b, axes=(-1,-2))
a=np.random.random(size=(3,4,5))
b=np.random.random(size=(3,5,7))
(a @ b).shape
np.sum(a[..., np.newaxis] * np.moveaxis(b[..., np.newaxis], -1,-3), axis=-2)
np.einsum('ii', a) # trace(a)
np.einsum('ii->i', a) #diag(a)
np.einsum('ijk,jkl', a, b) # tensordot(a,b)
np.einsum('ijk,ikl->ijl', a,b ) # matmul(a,b)
In [28]:
A=np.random.randint(0,10, size=(5,3))
A
Out[28]:
In [29]:
B=np.random.randint(0,10, size=(3,7))
B
Out[29]:
In [94]:
A.dot(B)
Out[94]:
numpy 以 ndarray 為中心
np.vectorize
把一般的函數變成逐項運算 )