简体   繁体   English

从Tensorflow中的tf.matmul(tf.transpose(A),A)中获取对角线元素

[英]Get diagonal elements from tf.matmul(tf.transpose(A), A) in Tensorflow

I have a matrix A with several columns, and I need to compute the self dot products, ie tf.matmul(A[:,i]), A[:,i], transpose_a=True) where i indexes columns of A . 我有一个包含几列的矩阵A ,我需要计算自点积,即tf.matmul(A[:,i]), A[:,i], transpose_a=True) ,其中i索引了A列。 One way is to just compute tf.matmul(A,A, transpose_a=True) and extract the diagonal, but this involves a lot of superfluous multiplication (all non-diagonal results are discarded, and the non-diagonal results are most of the results for any matrix larger than 2 x 2). 一种方法是只计算tf.matmul(A,A, transpose_a=True)并提取对角线,但这涉及很多多余的乘法(所有非对角线结果都被丢弃,并且非对角线结果是大多数任何大于2 x 2的矩阵的结果)。 Another way is to do something like 另一种方法是做类似的事情

out = []
for i in range(tf.shape(A)[1]):
    out.append(tf.matmul((A[:,i],A[:,i],transpose_a=True))

and then collect out into a tf.Tensor . 然后收集outtf.Tensor But it seems like this is a fairly common computation, so I would expect a function to exist for it (ie computing squared norms of weight vectors). 但是似乎这是一个相当普通的计算,因此我希望为此存在一个函数(即计算权重向量的平方范数)。

You can multiply the matrix by itself elementwise and then sum along axis 0. 您可以将矩阵本身按元素相乘,然后沿轴0相加。

import tensorflow as tf
tf.InteractiveSession()

A = tf.reshape(tf.range(12), (3, 4))
tf.reduce_sum(tf.pow(A, 2), axis=0).eval()

returns 回报

array([ 80, 107, 140, 179], dtype=int32)

Just a little bit of linear algebra and you have your solution: 只需一点线性代数,您就能找到解决方案: 在此处输入图片说明

Which means that you need to do: tf.reduce_sum(tf.square(A), axis=0) 这意味着您需要执行以下操作: tf.reduce_sum(tf.square(A), axis=0)

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

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