import numpy as np ''' https://github.com/cmudeeplearning11785/Spring2019_Tutorials/blob/master/recitation-0/Numpy%20%26%20PyTorch.ipynb 在python中调用numpy package主要是为了实现vectorization向量化的操作 假设现在要实现 y=wx+b 等式,分别写出在不适用numpy工具包和使用numoy工具包下的代码段 ''' def wx_b_nonp():#不适用numypy工具包,只使用python中的内部结构list实现 W = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] x = [7, 8, 5] b = [1, 1, 1] # Output y = [0, 0, 0] input_dim=len(x) output_dim=len(y) for i in range(output_dim): for j in range(input_dim): y[i]+=x[j]*W[i][j] y[i]+=b[i] return y def wx_b_np(): W = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) x = np.array([7, 8, 5]) b = np.array([1, 1, 1]) y=W.dot(x)+b return y output1=wx_b_nonp() output2=wx_b_np() print(output1,output2) '''[21, 41, 61] [21 41 61]''' T=np.random.random((2,3,4)) print(T) W=T[1] print(W.shape,W.dtype)#(3, 4) float64 X=np.full((4,3),11785,dtype=np.uint32) print(X.shape,X.dtype,np.min(X),np.max(X)) ''' (4, 3) uint32 11785 11785 ''' y=W.dot(X)#(3, 3) print(y.shape) X2=np.zeros(X.shape) is_true=np.array_equal(W.dot(X2),np.zeros((3,3)))#判断两个numpy数组是否相等 print(is_true)#True #numpy数组的element wise operations y=np.arange(10) out=(y==np.array(range(10))) print(out)#[ True True True True True True True True True True] out2=np.sqrt(y**2) y.min(), y.max(), y.std(), y.sum() np.save('1.npy',np.array(range(2*4*3)).reshape(2,4,3)) T=np.load('1.npy') print(T) #numpy也可以进行切片和索引 T1=np.array(range(12)).reshape(2,3,2) print(T1) print(T1%10==0) print(T1[T1%10==0])#numpy数组支持布尔索引 ''' [[[ 0 1] [ 2 3] [ 4 5]] [[ 6 7] [ 8 9] [10 11]]] [[[ True False] [False False] [False False]] [[False False] [False False] [ True False]]] [ 0 10] '''
CMU 11-785 recitation numpy操作
最新推荐文章于 2023-08-23 19:22:46 发布