Theano row/column 明智的减法

Theano row/column wise subtraction

X 是一个 n x d 矩阵,W 是一个 m x d 矩阵,对于 X 中的每一行,我想计算其中每一行的平方欧几里得距离W,因此结果将是一个 n x m 矩阵。

如果 W 只有一行,这很容易

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 中)时我该怎么办?

幸运的是W中的行数可以提前知道,所以我暂时做

x = tensor.TensorType("float64", [False, False])()
m = 2
w = tensor.as_tensor([[2,2,2],[1,2,3]])
res_list = []
for i in range(m):
    res_list.append(ten.sum((x-w[i,:])**2, axis=1))

z = tensor.stack(res_list)

fn = theano.function([x], z)
print fn([[1,2,3], [2,2,2], [2,3,4]])

# [[ 2.  0.  5.]
#  [ 0.  2.  3.]]

欢迎其他回答!

简答,使用scipy.spatial.distance.cdist

长答案,如果你没有 scipy,就是广播减法,然后按轴 0 进行范数。

np.linalg.norm(X[:,:,None]-W[:,None,:], axis=0)

真的很长的答案,你有一个没有可向量化的古老版本的 numpy linalg.norm(即你正在使用 Abaqus)是

np.sum((X[:,:,None]-W[:,None,:])**2, axis=0).__pow__(0.5)

OP 编辑​​
在 Theano 中,我们可以使 XW 都是 3d 矩阵,并使相应的轴像

一样可广播
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.]]