我正在尝试转换代码
import numpy as np
W_np = np.ones((2,2))
x_np = np.array([1,0])
print(W_np @ x_np)
output: array([1., 1.])
等效于TensorFlow
import tensorflow as tf
tf.enable_eager_execution()
W = tf.Variable(tf.ones(shape=(2,2)), name="W", dtype=tf.float32)
x = tf.Variable(np.array([1,0]), name = 'x', dtype=tf.float32)
W @ x
但收到错误消息
InvalidArgumentError: In[1] is not a matrix. Instead it has shape [2] [Op:MatMul] name: matmul/
如何解决?
答案 0 :(得分:1)
下一个应该工作:
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
W = tf.Variable(tf.ones(shape=(2,2)), name="W", dtype=tf.float32)
x = tf.Variable(np.array([1,0]), name = 'x', dtype=tf.float32)
res =tf.linalg.matmul(W, tf.expand_dims(x, 0), transpose_b=True)
print(res)
# tf.Tensor([[1.] [1.]], shape=(2, 1), dtype=float32)
# or slightly different way
res =tf.linalg.matmul(tf.expand_dims(x, 0), W)
res = tf.squeeze(res)
print(res)
# tf.Tensor([1. 1.], shape=(2,), dtype=float32)
答案 1 :(得分:1)
您还可以使用reshape():
import tensorflow as tf
tf.enable_eager_execution()
W = tf.Variable(tf.ones(shape=(2,2)), name="W", dtype=tf.float32)
x = tf.Variable(np.array([1,0]).reshape(-1,1), name = 'x', dtype=tf.float32)
res = tf.matmul(W,x)
print(res)
输出:
tf.Tensor([[1.]
[1.]], shape=(2, 1), dtype=float32)