简体   繁体   English

Tensorflow 2D 矩阵乘法返回矩阵乘积列表

[英]Tensorflow 2D Matrices mutiplication returning list of matrix products

I'm struggling with this problem in keras/tensorflow.我在 keras/tensorflow 中遇到了这个问题。
I'm implementing a user defined loss function and I have this problem: I have to multiply 2 matrices, obtaining a list of matrix products in the form我正在实现一个用户定义的损失 function 并且我遇到了这个问题:我必须将 2 个矩阵相乘,以表格形式获得矩阵乘积列表
[column_0_matrix_1 x row_0_matrix_2], [column_1_matrix_1 x row_1_matrix_2] ecc. [column_0_matrix_1 x row_0_matrix_2],[column_1_matrix_1 x row_1_matrix_2] ecc。

Let's say I have假设我有

A = [[1 1]
     [3 2]]
B = [[4 1]
     [1 3]]

Then I want to have a list of products in the form然后我想要表格中的产品列表

C = |[1] x [4 1]|, |[1] x [1 3]|
    |[3]        |  |[2]        |


Any idea?任何想法? I tried by my self but always get back the product of the 2 starting matrices.我自己尝试过,但总是取回 2 个起始矩阵的乘积。 Any help would by appreciated.任何帮助将不胜感激。 Thank you谢谢

You could split each tensor and then use tf.linalg.matmul in a list comprehension to achieve what you want您可以拆分每个张量,然后在列表理解中使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM