[英]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
. 然后收集
out
成tf.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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.