简体   繁体   English

尝试转换数学运算时MatMul排名错误

[英]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.

相关问题 当试图转换为浮点数来做数学时,它给了我一个错误 - When trying to convert to float to do math it gives me an error Matmul有不同的级别 - Matmul with different rank 尝试使用 skmultilearn.BinaryRelevance 预测新文本时出现 Matmul 错误 - Matmul error when trying to predict a new text using skmultilearn.BinaryRelevance ValueError:形状必须为 2 级,但“MatMul”为 1 级 - ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' ValueError:Shape必须是2级,但是'MatMul'的排名是3 - ValueError: Shape must be rank 2 but is rank 3 for 'MatMul' 尝试列表操作时的浮动对象错误 - Float object error when trying list operations 广播np.dot vs tf.matmul以进行张量矩阵乘法(形状必须为2级,但为3级错误) - Broadcasting np.dot vs tf.matmul for tensor-matrix multiplication (Shape must be rank 2 but is rank 3 error) 等级> 2的Tensorflow matmul操作不起作用 - Tensorflow matmul operation for rank>2 does not work 尝试对条目中提供的整数进行数学运算时出错 - Error when trying to do math on integers provided in an Entry 在尝试使用asin()时未定义名称'math'时出错 - Error saying that name 'math' is not defined when trying to use asin()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM