在实现一些算法时,数学表达式已经求出来了,需要将之转换为代码实现,简单的一些还好,有时碰到例如矩阵转置、矩阵乘法、求迹、张量乘法、数组求和等等,若是以分别以 transopse、sum、trace、tensordot 函数就是根据上面的标记法实现的一种函数,可以根据给定的表达式进行运算,可以替代但不限于以下函数: 矩阵求迹:trace 求矩阵对角线:diag 张量(沿轴)求和:sum 张量转置:transopose 矩阵乘法:dot 张量乘法:tensordot 最后,再测试 einsum 与另一个常用的函数 tensordot,首先定义两个四维张量的及 tensordot 函数: 该实现对应的公式为: ? 所以 einsum 函数的实现为: tensordot 也是链接到 BLAS 实现的函数,所以不加 optimize 肯定比不了,最后结果为: 测试了 10 多次,基本上速度一样,einsum 表现好一点的
3.张量缩并(Contraction)——推广的“乘法”(a)内积(点积)沿指定轴:np.tensordotnp.tensordot(A,B,axes)对A和B的指定轴求和。 经典例子:矩阵乘法是tensordot的特例:展开代码语言:PythonAI代码解释>C=np.tensordot(A,B,axes=([-1],[0]))#A:(m,n),B:(n,p)→C:(m,p )>3阶张量示例:展开代码语言:PythonAI代码解释#A:(2,3,4),B:(4,5,6)#想对A的第2轴(size=4)和B的第0轴(size=4)做缩并C=np.tensordot(A,B,axes 缩并A=np.random.rand(4,5)Z=np.tensordot(X,A,axes=([2],[0]))#(2,3,5)#4.einsum多种操作#转置X_t=np.einsum('ijk-> print("X_mode1shape:",X_mode1.shape)print("Innerproduct:",inner)八、总结概念说明张量=多维数组阶数=维度数基本运算加法、标量乘、广播核心乘法tensordot
=1)inner_product = p * qbi_interaction = inner_productattention_temp = tf.nn.relu(tf.nn.bias_add(tf.tensordot ,'relu',kernel_regularizer=l2(self.l2_reg_w))(bi_interaction)self.normalized_att_score = softmax(tf.tensordot attention_output = self.dropout(attention_output, training=training) # training,防止过拟合afm_out = self.tensordot
inner_product = p * q bi_interaction = inner_product attention_temp = tf.nn.relu(tf.nn.bias_add(tf.tensordot relu',kernel_regularizer=l2(self.l2_reg_w))(bi_interaction) self.normalized_att_score = softmax(tf.tensordot attention_output = self.dropout(attention_output, training=training) # training,防止过拟合 afm_out = self.tensordot
我最近遇到过这样的情况:在实现一个概率矩阵分解(PMF)推荐系统时,我必须将许多对矩阵U和V.T相乘,我的jupyte内核在调用numpy.tensordot来实现我的目标时崩溃了。
(★★★) (提示: np.tensordot) # Author: Stefan van der Walt p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones ((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # It works, because: # M is (p,n,n)
(★★★) (提示: np.tensordot) # Author: Stefan van der Walt p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones ((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # It works, because: # M is (p,n,n)
# the shape of `v` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size v = tf.tanh(tf.tensordot # For each of the timestamps its vector of size A from `v` is reduced with `u` vector vu = tf.tensordot
在一般情况下,使用np.tensordot(a,b,axis=1)就可以,但在更复杂的情况下,einsum速度更快,读写更容易。
timestamps; 17# the shape of `v` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size 18v = tf.tanh(tf.tensordot 19# For each of the timestamps its vector of size A from `v` is reduced with `u` vector 20vu = tf.tensordot
) # (batch,feature_size*feature_size) ->(batch, feature_size) interaction = tf.tensordot # x0 * (xl * w) # (batch, 1, feature_size) * (feature_size) -> (batch,1) transform = tf.tensordot
, name='b') with tf.Session() as sess: print(sess.run(tf.multiply(a, b))) print(sess.run(tf.tensordot
更快的batched_tensordot并使其在GPU上工作。 SoftmaxGrad grad 通过CorrMM在GPU上进行3D转换 CPU Max Pool支持padding和strides!
上述操作和 np.tensordot( A, B, axes=([0,1],[1,0]) ) 等效。 np.tensordot( A, B, axes=([0,1],[1,0]) ) array([[4400., 4730.], [4532., 4874.], [4664., NumPy 包中的 einsum 可以替代如下常用的运算, 矩阵求迹: trace 求矩阵对角线: diag 张量(沿轴)求和: sum 张量转置: transopose 矩阵乘法: dot 张量乘法: tensordot
sess.run(tf.multiply(a, b))) ⇒ [20 60] # element-wise multiplication print(sess.run(tf.tensordot
group-convolutions、strided group-convolutions、indexing、Embedding (lookup table)、small-mobilenet、softmax、tensordot
如函数dot和inner经常链接到BLAS例程可以超越einsum在速度方面,tensordot函数也可以与之相比。
expert_outputs = [expert(inputs) for expert in self.experts] # 加权聚合专家输出 return tf.tensordot
std', 'str', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'sys', 'take', 'tan', 'tanh', 'tensordot
(★★★) (提示: np.tensordot) # Author: Stefan van der Walt p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones ((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # It works, because: # M is (p,n,n)