[英]Tensorflow efficient pairwise inner product
In Tensorflow (python), given a matrix X of shape (nxd) , where each row is a data point, I would like to compute the pairwise inner products of these n data points, ie , the upper triangle of XX' . 在Tensorflow(python)中,给定一个形状矩阵X (nxd) ,其中每一行是一个数据点,我想计算这n个数据点的成对内积, 即 XX'的上三角形。
Of course I could compute the whole XX' and fetch its upper triangle, but this means I would compute the off-diagonal elements twice . 当然,我可以计算整个XX'并获取其上三角形,但这意味着我将计算两次非对角线元素。 How to compute these efficiently in Tensorflow (python) by computing the inner product only once per pair?
如何通过每对只计算一次内积来在Tensorflow(python)中有效地计算这些?
With numpy, you can do this: 有了numpy,你可以这样做:
import numpy as np
A = np.random.randn(5, 3)
inds = np.triu_indices(5) # upper triangle indices
# expensive way to do it
ipu1 = np.dot(A, A.T)[inds]
# possibly less expensive way to do it.
ipu2 = np.einsum('ij,ij->i', A[inds[0]], A[inds[1]])
print(np.allclose(ipu1, ipu2))
This outputs True. 这输出True。 Tensorflow does not have the triu_indices function build in, but it is not hard to write one if needed by looking at the numpy code.
Tensorflow没有内置triu_indices函数,但如果需要通过查看numpy代码来编写一个并不困难。 It does have einsum.
它确实有einsum。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.