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, 4, 15),b 的形状为 (7, 4, 5)。
我希望 c=np.dot(a,b) 的大小为 (7,5,15),如下所示:
c = np.zeros((7,15,5))
for i in range(7):
c[i,:,:] = np.dot(a[i,:,:].T , b[i,:,:])
但我正在寻找没有 for 循环的解决方案。类似于:
c = np.tensordot(a.reshape(4,7,5),b.reshape(7,4,15),axes=([1,0],[0,1]))
但是这个没有按预期工作。
我也试过这个:
newaxes_a=[2,0,1]
newaxes_b=[1,0,2]
newshape_a=(-1,28)
newshape_b=(28,-1)
a_t = a.transpose(newaxes_a).reshape(newshape_a)
b_t = b.transpose(newaxes_b).reshape(newshape_b)
c = np.dot(a_t, b_t)
没有按预期工作。
有什么想法吗?
你可以使用np.einsum
-
#to match the given example
c2 = np.einsum('ijk,ijl->ikl',a,b)
print np.allclose(c, c2)
另一个使用 broadcasting
-
c = (a[:,:,None,:]*b[...,None]).sum(1)
我有两个 3dim numpy 矩阵,我想根据一个轴做点积而不使用循环:
a=[ [[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[ [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 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 0, 0.],
[ 0, 0, 0, 0, 0.],
[ 0, 1, 0, 0, 0.]],
[[ 0, 0, 1, 0, 0.],
[ 1, 0, 0, 0, 0.],
[ 0, 0, 0, 0, 0.],
[ 0, 1, 0, 0, 0.]],
[[ 0, 0, 1, 0, 0.],
[ 1, 0, 0, 0, 0.],
[ 0, 0, 0, 0, 0.],
[ 0, 1, 0, 0, 0.]],
[[ 0, 0, 1, 0, 0.],
[ 1, 0, 0, 0, 0.],
[ 0, 0, 0, 0, 0.],
[ 0, 1, 0, 0, 0.]],
[[ 0, 0, 1, 0, 0.],
[ 1, 0, 0, 0, 0.],
[ 0, 0, 0, 0, 0.],
[ 0, 1, 0, 0, 0.]]]
dt = np.dtype(np.float32)
a=np.asarray(a,dtype=dt)
b=np.asarray(b,dtype=dt)
print(a.shape)
print(b.shape)
a 的形状为 (7, 4, 15),b 的形状为 (7, 4, 5)。 我希望 c=np.dot(a,b) 的大小为 (7,5,15),如下所示:
c = np.zeros((7,15,5))
for i in range(7):
c[i,:,:] = np.dot(a[i,:,:].T , b[i,:,:])
但我正在寻找没有 for 循环的解决方案。类似于:
c = np.tensordot(a.reshape(4,7,5),b.reshape(7,4,15),axes=([1,0],[0,1]))
但是这个没有按预期工作。
我也试过这个:
newaxes_a=[2,0,1]
newaxes_b=[1,0,2]
newshape_a=(-1,28)
newshape_b=(28,-1)
a_t = a.transpose(newaxes_a).reshape(newshape_a)
b_t = b.transpose(newaxes_b).reshape(newshape_b)
c = np.dot(a_t, b_t)
没有按预期工作。
有什么想法吗?
你可以使用np.einsum
-
#to match the given example
c2 = np.einsum('ijk,ijl->ikl',a,b)
print np.allclose(c, c2)
另一个使用 broadcasting
-
c = (a[:,:,None,:]*b[...,None]).sum(1)