且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

tensorflow中张量乘法向量的matmul函数

更新时间:2021-12-08 10:12:05

你可以这样做:

tf.reduce_sum(tf.expand_dims(v,2)*T,1)

代码:

m, n, k = 2, 3, 4
T = tf.Variable(tf.random_normal((m,n,k)), name="tensor") 
v = tf.Variable(tf.random_normal((1,n)), name="vector")  


c = tf.stack([v,v]) # m times, here set m=2    
out1 = tf.matmul(c,T) 

out2 = tf.reduce_sum(tf.expand_dims(v,2)*T,1)
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  n_out1 = sess.run(out1) 
  n_out2 = sess.run(out2)
  #both n_out1 and n_out2 matches