python - 如何在张量流中用 3d 张量对 2d 张量进行 matmul?
问题描述
在numpy
您可以将 2d 数组与 3d 数组相乘,如下例所示:
>>> X = np.random.randn(3,5,4) # [3,5,4]
... W = np.random.randn(5,5) # [5,5]
... out = np.matmul(W, X) # [3,5,4]
据我了解np.matmul()
,W
沿X
. 但在tensorflow
其中是不允许的:
>>> _X = tf.constant(X)
... _W = tf.constant(W)
... _out = tf.matmul(_W, _X)
ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_1' (op: 'MatMul') with input shapes: [5,5], [3,5,4].
那么np.matmul()
上面的内容是否有等价物tensorflow
?tensorflow
将 2d 张量与 3d 张量相乘的最佳做法是什么?
解决方案
在乘法之前尝试使用tf.tile来匹配矩阵的维度。numpy 的自动广播功能似乎没有在tensorflow 中实现。您必须手动完成。
W_T = tf.tile(tf.expand_dims(W,0),[3,1,1])
这应该可以解决问题
import numpy as np
import tensorflow as tf
X = np.random.randn(3,4,5)
W = np.random.randn(5,5)
_X = tf.constant(X)
_W = tf.constant(W)
_W_t = tf.tile(tf.expand_dims(_W,0),[3,1,1])
with tf.Session() as sess:
print(sess.run(tf.matmul(_X,_W_t)))
推荐阅读
- c# - 来自 Html Agility Pack 的 LoadFromWebAsync 的异步 NullRefrenceException
- csv - 处理 CSV 文件中包含逗号的数据
- c++ - 可以用内部链接修改 const ......在外部?
- react-native - 与@expo/vector-icons 开玩笑会导致异步错误?
- reactjs - 如何在反应表中设置默认排序?
- keycloak - keycloak - 是否可以让用户在登录页面中选择一个领域
- php - 用php查询多个elasticsearch索引
- c# - 将我的 JSON 反序列化为 POCO 不会填充几个字段
- python - 从 pip 导入的包安装了一个而不是本地文件?
- angular - Mat Table - renderRows 单元测试错误