[英]MatMul rank error when trying to convert math operations
I have a script and I am trying to convert my math operations from NumPy operations to TensorFlow operations so it can get faster on GPU. 我有一个脚本,我正在尝试将我的数学运算从NumPy运算转换为TensorFlow运算,以便它可以在GPU上更快地运行。 And in my script I end up in a situation that I have an array with shape (260) and need to do matrix multiplication with another array with shape (260), illustrated by:
在我的脚本中,我最终遇到这样的情况:我有一个形状为(260)的数组,并且需要与另一个形状为(260)的数组进行矩阵乘法,如下所示:
import numpy as np
x = np.array([2] * 260)
y = np.array([4] * 260)
r = np.matmul(x,y) #np.dot(x,y) also works
print(r) #2080
But the same operation in TensorFlow is not possible. 但是TensorFlow中的相同操作是不可能的。
import tensorflow as tf
x = tf.Variable([2] * 260)
y = tf.Variable([4] * 260)
r = tf.matmul(x,y)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
result = sess.run(r)
print(result) # ERRROR
The TensorFlow error says: TensorFlow错误显示:
ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [260], [260].
ValueError:形状必须为2级,但输入形状为[260],[260]的“ MatMul”(操作:“ MatMul”)为1级。
I have tried to reshape the inputs countless many ways, and none of those have worked, such as: x = tf.expand_dims(x,1)
. 我尝试了无数种方法来重塑输入,但是这些方法都没有起作用,例如:
x = tf.expand_dims(x,1)
。
Since both inputs are 1-dimensional, your matrix multiplication is the inner product, 由于两个输入都是一维的,所以矩阵乘法就是内积,
tf.reduce_sum(tf.multiply(x, y))
or 要么
tf.tensordot(x, y, 1)
Also see this answer for a few alternative ways of calculating the inner product. 另请参阅此答案 ,以了解一些计算内积的替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.