如何用形状(2,2)和(2,)将两个TF.变量类型阵列乘以



我正在尝试转换代码

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/

如何解决它?

下一个应该起作用:

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)

您也可以使用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)

最新更新