深度学习基础知识 |
您所在的位置:网站首页 › 张量基本知识 › 深度学习基础知识 |
在计算机中,所有程序都可以简化为二进制输入上的一些二进制运算(与或非等); 在深度神经网络中,所有变换也可以简化为数值数据张量上的一些张量运算。 output = relu(dot(w,input) + b) 1、dot(w,input)为输入张量与张量w之间的点积运算。 2、dot(w,input) + b为得到的2D张量与张量b之间的加法运算 3、最后进行relu(x)运算。relu(x)为max(x,0)。 逐元素运算1、什么是逐元素运算? 该运算独立的应用于张量中的每个元素,如:relu运算和加法。 2、通过for循环对relu运算的简单实现: def naive_relu(x): #加法运算函数 assert len(x.shape)==2 #x是一个NUMPY的2D张量,assert检查条件,不符合就终止程序 x=x.copy() #避免覆盖输入张量,copy() 函数返回一个字典的浅复制。 for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] = max(x[i,j],0) #加法运算 return x通过for循环对加法运算的简单实现: def naive_add(x,y): #加法运算函数 assert len(x.shape)==2 #x是一个NUMPY的2D张量,assert检查条件,不符合就终止程序 assert x.shape==y.shape x=x.copy() #避免覆盖输入张量,copy() 函数返回一个字典的浅复制。 for i in range(x.shape[0]): for j in range(x.shape[1]): x[i,j] += y[i,j] #加法运算 return x3、在pycharm中可以直接运算 import numpy as np x = np.array([[1,3,6,2,7],[1,3,2,6,8],[1,2,5,1,4]]) y = np.array([[0,2,1,1,0],[0,5,2,1,2],[0,0,1,1,0]]) z=x+y print(z) z = np.maximum(z,0.) #relu运算 print(z)[[ 1 5 7 3 7] [ 1 8 4 7 10] [ 1 2 6 2 4]] [[ 1. 5. 7. 3. 7.] [ 1. 8. 4. 7. 10.] [ 1. 2. 6. 2. 4.]] 注:仅仅实现两个形状相同的2D张量的运算 广播当两个不同形状的张量相加时,形状较小的张量会被广播。 1)向较小的张量添加广播轴,使其nidm与较大张量相同。 2)将较小的张量沿着轴重复。 def naive_add_matrix_and_vector(x,y): assert len(x.shape) ==2 assert len(y.shape) ==1 assert x.shape[1] == y.shape[0] x = x.copy() for i in range(x.shape[0]): for j in range(x.shape): x[i,j]+=y[j] return x实际应用: import numpy as np x = np.random.random([64,3,32,10]) y = np.random.random([32,10]) x = np.random.random((4,3,32,10)) y = np.random.random((32,10)) x = np.random.rand(4,3,32,10) y = np.random.rand(32,10) z = np.maximum(x,y) print(z.shape) print(z) 张量点积(tensor product)实际应用: import numpy as np x = np.array([1,2,3]) y = np.array([4,2,8]) z = np.dot(x,y) print(z) x = np.array([[1,2,3],[1,3,1]]) y = np.array([4,2,8]) z = np.dot(x,y) print(z) x = np.array([[1,2,3],[1,3,1],[1,2,3]]) y = np.array([[4,2,8],[1,2,3],[2,3,1]]) z = np.dot(x,y) print(z)32 [32 18] [[12 15 17] [ 9 11 18] [12 15 17]] 从数学角度看待: def naive_vector_dot(x,y): assert len(x.shape)==1 assert len(y.shape)==1 assert x.shape[0]==y.shape[0] z=0. for i in range(x.shape[0]): z+=x[i]*y[i] return z注:两个向量之间的点积是一个标量,元素个数相同的向量才能做点积。 矩阵和向量之间的点击为向量。 两个矩阵间只有x.shape[1]==y.shape[0]才能做点积(dot(x,y))得到一个(x.shape[0],y.shape[1])的矩阵。 def naive_matrix_vector_dot(x,y): assert len(x.shape)==2 assert len(y.shape)==1 assert x.shape[1]==y.shape[0] z=np.zeros(x.shape[0]) for i in range(x.shape[0]): for j in range(x.shape[1]): z[i]+=x[i,j]*y[j] return z 张量变形1、张量的变形是指改变张量的行和列,以得到想要的形状。 import numpy as np x =np.array([[0.,1.],[2.,3.],[4.,5.]]) print(x.shape) x=x.reshape((6,1)) print(x)(3, 2) [[0.] [1.] [2.] [3.] [4.] [5.]] 2、转置 即将行列互换 import numpy as np x = np.array([[1,2,3],[1,2,2],[2,3,1]]) print(x) x=np.transpose(x) print(x)[[1 2 3] [1 2 2] [2 3 1]] [[1 1 2] [2 2 3] [3 2 1]] |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |