首页 文章

Tensorflow,如何通过1D向量中的相应元素乘以2D张量(矩阵)

提问于
浏览
1

我有一个形状 [batch x dim] 的二维矩阵 M ,我有一个形状为 [batch] 的矢量 V . 如何将矩阵中的每个列乘以V中的相应元素?那是:

enter image description here

我知道一个低效的numpy实现看起来像这样:

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)

在张量流中,给定两个张量,实现这一目标的最有效方法是什么?

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)

2 回答

  • 5

    在NumPy中,我们需要制作 V 2D 然后让广播进行逐元素乘法(即Hadamard乘积) . 我猜,它应该在 tensorflow 上相同 . 因此,为了扩展 tensorflow 上的dims,我们可以使用 tf.newaxis (在较新版本上)或 tf.expand_dims 或使用 tf.reshape 重塑 -

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

    除了@Divakar的答案之外,我还要注意 MV 的顺序无关紧要 . 似乎 tf.multiply 也做broadcasting during multiplication .

    例:

    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)
    

相关问题