python - 二维和三维张量的乘法
问题描述
有一个二维张量a[m,n]
和一个三维张量b[k,n,h]
。我应该使用什么 API 将二维张量乘以三维张量以获得三维张量c[k,m,h]
?
其实我可以通过:
import tensorflow as tf
import tensorly as tl
x = tf.constant([[[1,2],[3,7],[8,9]],
[[4,5],[6,10],[11,12]]],tf.float32)
a = tf.constant([[-0.70711,0.57735],
[0.0000,0.57735],
[0.70711,0.57735]])
reshape_A = tf.reshape(x, [2,6])
re = tf.reshape(tf.matmul(a, reshape_A), [3, 3, 2])
with tf.Session() as sess:
print(sess.run(re))
re = re.eval()
但是有没有更简单的方法?
解决方案
您可以使用tensorly.tenalg.contract。对于您的示例:
import tensorly as tl
import numpy as np
tl.set_backend('tensorflow')
k = 2; m = 3; n = 5; h = 4
A = tl.tensor(np.random.random((m, n)))
B = tl.tensor(np.random.random((k, n, h)))
res = tl.tenalg.contract(A, 1, B, 1)
推荐阅读
- javascript - 如何根据对象数组中字段的最大值限制 HTML 列元素
- c# - 将 varchar 转换为 int mvc C# 时转换失败
- php - 从 MySQL、PHP 获取随机结果
- ios - Xcode - 工具栏或视图未显示在顶部附近
- r - 无法安装软件包,因为“无法构建 stringi。检查您的编译器标志”
- javascript - 确定字符串中的最外层范围是否是 JavaScript 语言中的函数
- ngrok - 隧道 ---------ngrok.io 未找到
- json - JSONObject 和 Streams/Lambda
- pdfbox - Apache PDFBOX renderImageWithDPI UTF-8 问题
- flutter - 如何在屏幕中正确放置 CustomPainter 动画?