Theano行/列明智的减法 [英] Theano row/column wise subtraction

查看:77
本文介绍了Theano行/列明智的减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中,我们可以将XW都设置为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆