首页 文章

许多矩阵与向量的乘法和张量流中得到的向量的总和

提问于
浏览
0

我试图将一组向量与相应的矩阵相乘,并希望在结尾处对得到的向量求和 . 作为一个简单的例子,让我们假设我们有20个矢量和矩阵分别为10x1和150x1:

import numpy as np
np_b=[ np.random.rand(10) for i in range(20)]
np_A=[ np.random.rand(150,10) for i in range(20)]
#first we multiply each vector with it's corresponding matrix
np_allMuls=np.array([np.dot(np_A[i],np_b[i]) for i in range(20)] ) 
#then we sum all of the vectors to get the 150 dimensional sum vector
np_allSum=np.sum( np_allMuls,axis=0 )

到目前为止,我已得到张量流0.10:

import tensorflow as tf
tf_b = tf.placeholder("float", [None,10])
tf_A= tf.placeholder("float", [None,150,10])
#the following gives me ValueError: Shape (?, 150, 10) must have rank 2
tf_allMuls=tf.matmul(tf_A,tf_b)

但是这个符号乘法给出了错误“ValueError:Shape(?,150,10)必须具有等级2” .

有谁知道为什么我收到这样的错误信息?我怎样才能正确获得tf_allMuls?

1 回答

  • 1

    tf.matmul的文档:

    输入必须是矩阵(或秩> 2的张量,代表批量矩阵),具有匹配的内部维度,可能在换位之后 .

    考虑到您使用 None 作为占位符的第一个参数,第二个选项与您相关,即"batches of matrices" . 但是你的 tf_b 是一批向量,而不是矩阵,所以两个矩阵的等级不一样,这就是你得到错误的原因 . 您应该使用:

    tf_b = tf.placeholder("float", [None, 10, 1])
    tf_A = tf.placeholder("float", [None, 150, 10])
    tf_allMuls = tf.matmul(tf_A, tf_b)
    

    因此似乎 matmul 无法广播(可能会检查此post)并且我同意您收到的错误消息有点误导 .

    这是一个简单的例子:

    tf_b = tf.placeholder("float", [None, 3, 1])
    tf_A = tf.placeholder("float", [None, 3, 3])
    tf_allMuls = tf.matmul(tf_A, tf_b)
    
    with tf.Session() as sess:
        b = np.array([1, 2, 3])[np.newaxis, :, np.newaxis]
        A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])[np.newaxis, ...]
        muls = sess.run(tf_allMuls, feed_dict={tf_b: b, tf_A: A})
        print muls
    

    打印

    [[[ 14.]
      [ 32.]
      [ 50.]]]
    

    另请注意, tf.matmul 的参数顺序非常重要,就像您习惯于实际的矩阵乘法一样 . 所以虽然这样

    tf_b = tf.placeholder("float", [None, 1, 3])
    tf_A = tf.placeholder("float", [None, 3, 3])
    tf_allMuls = tf.matmul(tf_A, tf_b)
    

    不工作,以下会(当然,它不是计算相同的东西,但它不会引发错误):

    tf_b = tf.placeholder("float", [None, 1, 3])
    tf_A = tf.placeholder("float", [None, 3, 3])
    tf_allMuls = tf.matmul(tf_b, tf_A)
    

相关问题