[英]Tensorflow 2D Matrices mutiplication returning list of matrix products
我在 keras/tensorflow 中遇到了这个问题。
我正在实现一个用户定义的损失 function 并且我遇到了这个问题:我必须将 2 个矩阵相乘,以表格形式获得矩阵乘积列表
[column_0_matrix_1 x row_0_matrix_2],[column_1_matrix_1 x row_1_matrix_2] ecc。
假设我有
A = [[1 1]
[3 2]]
B = [[4 1]
[1 3]]
然后我想要表格中的产品列表
C = |[1] x [4 1]|, |[1] x [1 3]|
|[3] | |[2] |
任何想法? 我自己尝试过,但总是取回 2 个起始矩阵的乘积。 任何帮助将不胜感激。 谢谢
您可以拆分每个张量,然后在列表理解中使用tf.linalg.matmul来实现您想要的
import tensorflow as tf
a = tf.constant([[1, 1], [3, 2]])
b = tf.constant([[4, 1], [1, 3]])
a_split = tf.split(a, 2, 1)
b_split = tf.split(b, 2, 0)
[tf.linalg.matmul(x, y) for x, y in zip(a_split, b_split)]
# [<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
# array([[ 4, 1],
# [12, 3]], dtype=int32)>,
# <tf.Tensor: shape=(2, 2), dtype=int32, numpy=
# array([[1, 3],
# [2, 6]], dtype=int32)>]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.