Theano行/列明智的减法 [英] Theano row/column wise subtraction
问题描述
X
是n×d矩阵,W
是m×d矩阵,对于X
中的每一行,我想计算W
中每一行的平方欧几里德距离,因此结果将是是一个n×m矩阵.
X
is an n by d matrix, W
is an m by d matrix, for every row in X
I want to compute the squared Euclidean distance with every row in W
, so the results will be an n by m matrix.
如果W
中只有一行,这很容易
If there's only one row in W
, this is easy
x = tensor.TensorType("float64", [False, False])()
w = tensor.TensorType("float64", [False])()
z = tensor.sum((x-w)**2, axis=1)
fn = theano.function([x, w], z)
print fn([[1,2,3], [2,2,2]], [2,2,2])
# [ 2. 0.]
W
是矩阵(在Theano中)怎么办?
What do I do when W
is a matrix (in Theano)?
推荐答案
Short answer, use scipy.spatial.distance.cdist
如果没有技巧,那么长的答案是先播出减法,然后再进行0轴范数化.
Long answer, if you don't have scipy, is to broadcast subtract and then norm by axis 0.
np.linalg.norm(X[:,:,None]-W[:,None,:], axis=0)
答案很长,您有一个古老版本的numpy,但没有可向量化的linalg.norm
(即您使用的是Abaqus)是
Really long answer, of you have an ancient version of numpy without a vecorizable linalg.norm
(i.e. you're using Abaqus) is
np.sum((X[:,:,None]-W[:,None,:])**2, axis=0).__pow__(0.5)
由OP编辑
在Theano中,我们可以将X
和W
都设置为3d矩阵,并使相应的轴可广播,如
Edit by OP
In Theano we can make X
and W
both 3d matrices and make the corresponding axes broadcastable like
x = tensor.TensorType("float64", [False, True, False])()
w = tensor.TensorType("float64", [True, False, False])()
z = tensor.sum((x-w)**2, axis=2)
fn = theano.function([x, w], z)
print fn([[[0,1,2]], [[1,2,3]]], [[[1,1,1], [2,2,2]]])
# [[ 2. 5.]
# [ 5. 2.]]
这篇关于Theano行/列明智的减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!