当前位置: 代码迷 >> python >> 张量流中众多矩阵与向量的相乘以及所得向量的求和
  详细解决方案

张量流中众多矩阵与向量的相乘以及所得向量的求和

热度:33   发布时间:2023-06-13 15:20:11.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 )

到目前为止,使用tensorflow 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?

从的文档中:

输入必须是矩阵(或等级大于2的张量,表示矩阵的批次),并且可能在转置后具有匹配的内部尺寸。

考虑到您使用None作为占位符的第一个参数,因此第二个选项与您相关,即“矩阵批”。 但是您的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无法广播(可以查看此 ),我同意您收到的错误消息有点误导。

这是一个简单的示例:

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.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)
  相关解决方案