matmul function for vector with tensor multiplication in tensorflow

丶灬走出姿态 提交于 2019-12-25 00:05:21

问题


In general when we multiply a vector v of dimension 1*n with a tensor T of dimension m*n*k, we expect to get a matrix/tensor of dimension m*k/m*1*k. This means that our tensor has m slices of matrices with dimension n*k, and v is multiplied to each matrix and the resulting vectors are stacked together. In order to do this multiplication in tensorflow, I came up with the following formulation. I am just wondering if there is any built-in function that does this standard multiplication straightforward?

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
output = tf.matmul(c,T)

回答1:


You can do it with:

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

Code:

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



回答2:


Not sure if there is a better way, but it sounds like you could use tf.map_fn like this:

 output = tf.map_fn(lambda x: tf.matmul(v, x), T)


来源:https://stackoverflow.com/questions/50300972/matmul-function-for-vector-with-tensor-multiplication-in-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!