python矩阵对应元素相乘,Tensorflow,如何将2D张量(矩阵)与1D向量中的对应元素相乘...

I have a 2D matrix M of shape [batch x dim], I have a vector V of shape [batch]. How can I multiply each of the columns in the matrix by the corresponding element in the V? That is:

18750e013dbb476fcf8bc7bfbb24e4f1.png

I know an inefficient numpy implementation would look like this:

import numpy as np

M = np.random.uniform(size=(4, 10))

V = np.random.randint(4)

def tst(M, V):

rows = []

for i in range(len(M)):

col = []

for j in range(len(M[i])):

col.append(M[i][j] * V[i])

rows.append(col)

return np.array(rows)

In tensorflow, given two tensors, what is the most efficient way to achieve this?

import tensorflow as tf

sess = tf.InteractiveSession()

M = tf.constant(np.random.normal(size=(4,10)), dtype=tf.float32)

V = tf.constant([1,2,3,4], dtype=tf.float32)

解决方案

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)))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值