Tensorflow, how to multiply a 2D tensor (matrix) by corresponding elements in a 1D vector

霸气de小男生 提交于 2019-11-30 16:16:45
Divakar

In NumPy, we would need to make V 2D and then let broadcasting do the element-wise multiplication (i.e. Hadamard product). I am guessing, it should be the same on tensorflow. So, for expanding dims on tensorflow, we can use tf.newaxis (on newer versions) or tf.expand_dims or a reshape with tf.reshape -

tf.multiply(M, V[:,tf.newaxis])
tf.multiply(M, tf.expand_dims(V,1))
tf.multiply(M, tf.reshape(V, (-1, 1)))

In addition to @Divakar's answer, I would like to make a note that the order of M and V don't matter. It seems that tf.multiply also does broadcasting during multiplication.

Example:

In [55]: M.eval()
Out[55]: 
array([[1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]], dtype=int32)

In [56]: V.eval()
Out[56]: array([10, 20, 30], dtype=int32)

In [57]: tf.multiply(M, V[:,tf.newaxis]).eval()
Out[57]: 
array([[ 10,  20,  30,  40],
       [ 40,  60,  80, 100],
       [ 90, 120, 150, 180]], dtype=int32)

In [58]: tf.multiply(V[:, tf.newaxis], M).eval()
Out[58]: 
array([[ 10,  20,  30,  40],
       [ 40,  60,  80, 100],
       [ 90, 120, 150, 180]], dtype=int32)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!