Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将两个tf.可变类型数组与形状(2,2)和(2,)相乘?_Python_Python 3.x_Numpy_Tensorflow - Fatal编程技术网

Python 如何将两个tf.可变类型数组与形状(2,2)和(2,)相乘?

Python 如何将两个tf.可变类型数组与形状(2,2)和(2,)相乘?,python,python-3.x,numpy,tensorflow,Python,Python 3.x,Numpy,Tensorflow,我试图转换代码 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.]) 张量流等价 import tensorflow as tf tf.enable_eager_execution() W = tf.Variable(tf.ones(shape=(2,2)), name="W", dtype=tf.float32) x = tf.Va

我试图转换代码

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.])
张量流等价

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)
也可以使用重塑()

输出:

tf.Tensor([[1.]
           [1.]], shape=(2, 1), dtype=float32)

numpy
matmul
对1d数组(您的(2,)形状)有特殊处理。查看其文档。
tensorflow
版本可能无法再次检查其文档。
tf.Tensor([[1.]
           [1.]], shape=(2, 1), dtype=float32)