简体   繁体   English

如何在Tensorflow中计算矩阵乘积的对角线?

[英]How to calculate diagonal of a matrix product in Tensorflow?

I have two matrices A and B of shape (M, N) with very large M and small N . 我有两个矩阵AB形状的(M, N)具有非常大的M和小N

I would like to multiply them and then take diagonal of a result: 我想将它们相乘,然后取结果的对角线:

C = tf.matmul(A, B)
D = tf.diag_part(C)

Unfortunately, this requires of creating of very big (M, M) matrix, which can't fit into memory. 不幸的是,这需要创建非常大的(M, M)矩阵,该矩阵无法容纳到内存中。

But most of this data I don't need. 但是我不需要大多数此类数据。 So, is it possible to calculate this value in one step? 因此,可以一步计算此值吗?

Is there something like einsum but without summing? 是否有类似einsum但未求和?

What you need is equivalent to: 您所需要的等同于:

tf.einsum('ij,ij->i', A, B)

or: 要么:

tf.reduce_sum(A * B, axis=1)

Example : 范例

A = tf.constant([[1,2],[2,3],[3,4]])
B = tf.constant([[3,4],[1,2],[2,3]])

with tf.Session() as sess:
    print(sess.run(tf.diag_part(tf.matmul(A, B, transpose_b=True)))) 
# [11  8 18]

with tf.Session() as sess:
    print(sess.run(tf.reduce_sum(A * B, axis=1)))
#[11  8 18]

with tf.Session() as sess:
    print(sess.run(tf.einsum('ij,ij->i', A, B)))
#[11  8 18]

You can use the dot product of A and B transpose to obtain the same: 您可以使用AB transposedot product获得相同的结果:

tf.reduce_sum(tf.multiply(A, tf.transpose(B)), axis=1)

The code: 编码:

import tensorflow as tf
import numpy as np

A = tf.constant([[1,4, 3], [4, 2, 6]])
B = tf.constant([[5,4,],[8,5], [7, 3]])

E = tf.reduce_sum(tf.multiply(A, tf.transpose(B)), axis=1)

C = tf.matmul(A, B)
D = tf.diag_part(C)
sess = tf.InteractiveSession()

print(sess.run(D))
print(sess.run(E))

#Output
#[58 44]
#[58 44]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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