Tensorflow N-D张量矩阵与张量流相乘
假设我有一组向量Tensorflow N-D张量矩阵与张量流相乘,tensorflow,matrix-multiplication,tensor,Tensorflow,Matrix Multiplication,Tensor,假设我有一组向量a,我想将a中的每个向量乘以一个张量T,最后得到一个张量y,其中每个切片矩阵是a中的向量v与T相乘的结果: A = tf.constant([1,2,3,4], shape=[2,2], dtype=tf.float32) #v1 =[1,2], v2=[3,4] T = tf.constant([1,2,3,4,5,6,7,8], shape=[2,2,2], dtype=tf.float32) [[[ 7. 10.] [19. 22.]] [[15. 22.]
a
,我想将a
中的每个向量乘以一个张量T
,最后得到一个张量y
,其中每个切片矩阵是a
中的向量v
与T
相乘的结果:
A = tf.constant([1,2,3,4], shape=[2,2], dtype=tf.float32) #v1 =[1,2], v2=[3,4]
T = tf.constant([1,2,3,4,5,6,7,8], shape=[2,2,2], dtype=tf.float32)
[[[ 7. 10.]
[19. 22.]]
[[15. 22.]
[43. 50.]]]
如果X
仅包含一个向量,则以下代码有效(感谢中的答案):
但是如果X由几个向量组成,那么乘法的代码是什么呢
例如,对于A
(带有2
向量)和T
,我有以下值:
A = tf.constant([1,2,3,4], shape=[2,2], dtype=tf.float32) #v1 =[1,2], v2=[3,4]
T = tf.constant([1,2,3,4,5,6,7,8], shape=[2,2,2], dtype=tf.float32)
[[[ 7. 10.]
[19. 22.]]
[[15. 22.]
[43. 50.]]]
我想通过将A
乘以T
得到以下输出:
A = tf.constant([1,2,3,4], shape=[2,2], dtype=tf.float32) #v1 =[1,2], v2=[3,4]
T = tf.constant([1,2,3,4,5,6,7,8], shape=[2,2,2], dtype=tf.float32)
[[[ 7. 10.]
[19. 22.]]
[[15. 22.]
[43. 50.]]]
这个问题的一个应用是线性回归中的批梯度下降法,其中我有一组向量,但不是训练权重矩阵,而是训练张量T
,因此输出y
将是一个张量,其中张量中的每个矩阵都是输入向量与T
相乘的输出
注意,一般来说,当我们将维度为1*n
的向量v
与维度为m*n*k
的张量T
相乘时,我们期望得到维度为m*k/m*1*k
的矩阵/张量。这意味着我们的张量有m
个维度为n*k
的矩阵切片,并且v
与每个矩阵相乘,得到的向量叠加在一起。尝试:
或者
eval
'
array([[[ 7., 10.],
[19., 22.]],
[[15., 22.],
[43., 50.]]], dtype=float32)
哦,非常感谢,这么简单的解决方案。我无法在
tf.tensordot