张量流矩阵乘法

问题描述 投票:0回答:2

所以,我想将一个矩阵与一个矩阵相乘。当我尝试使用矩阵的数组时,它有效:

import tensorflow as tf

x = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.ones([3, 3]))
y = tf.matmul(x, W)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    curr_y = sess.run(y, feed_dict={x: [[1,2,3],[0,4,5]]})
    print curr_y

因此数组的批量大小为 2,形状为 3x1。所以我可以将形状为 3x3 的矩阵与数组 3x1 相乘。 但是当我再次有一个形状为 3x3 的矩阵,但这次是一个矩阵而不是形状为 3x2 且批量大小为 2 的数组时,它不起作用。

但是如果我尝试将一个矩阵与一个矩阵相乘。没用。

import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 3,3])
W = tf.Variable(tf.ones([3, 3]))
y = tf.matmul(x, W)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    curr_y = sess.run(y, feed_dict={x: [[[1,2,3],[1,2,3]],[[1,1,4],[0,4,5]]]})
    print curr_y

ValueError:形状必须为 2 级,但“MatMul”为 3 级(操作: 'MatMul'),输入形状:[?,3,3], [3,3]。

########编辑

抱歉,我想做的是,将一个矩阵与一批矩阵或数组相乘。所以我不想做

y = tf.matmul(x, W)

其实我也想做

y = tf.matmul(W, x)
python matrix tensorflow
2个回答
0
投票

您对张量“x”的输入具有形状 (2, 2, 3)。 您正在尝试进行 (2, 2, 3) 和 (3, 3) 的矩阵乘法。他们没有相同的排名,这就是错误的原因。

来自Tensorflow官方网站: https://www.tensorflow.org/api_docs/python/tf/matmul

Args:

a: Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
b: Tensor with same type and rank as a.

0
投票

进行矩阵乘法时,矩阵的

shape
需要遵循规则
(a, b) * (b, c) = (a, c)

请记住您定义的 W 的形状是 (3, 3)。

这个

feed_dict={x: [[1,2,3],[0,4,5]]}
是一个2D数组,它的形状是(2, 3)

In [67]: x = [[1, 2, 3], [0, 4, 5]]

In [68]: x = np.array(x)

In [69]: x.shape
Out[69]: (2, 3)

遵循规则

(2, 3) * (3, 3) => (2, 3)

但是你的第二个例子,形状不遵循乘法规则。您输入的形状是 (2, 2, 3),它甚至与您定义的 W 不在同一维度,因此它不起作用。

In [70]: foo = [[[1,2,3],[1,2,3]],[[1,1,4],[0,4,5]]]

In [71]: foo = np.array(foo)

In [72]: foo.shape
Out[72]: (2, 2, 3)
© www.soinside.com 2019 - 2024. All rights reserved.