【发布时间】:2017-11-06 22:43:24
【问题描述】:
问题:
我想计算一组非常大的数据的点积。我可以在嵌套的 for 循环中执行此操作,但这太慢了。 这是一个小例子:
import numpy as np
points = np.array([[0.5, 2, 3, 5.5, 8, 11], [1, 2, -1.5, 0.5, 4, 5]])
lines = np.array([[0, 2, 4, 6, 10, 10, 0, 0], [0, 0, 0, 0, 0, 4, 4, 0]])
x1 = lines[0][0:-1]
y1 = lines[1][0:-1]
L1 = np.asarray([x1, y1])
# calculate the relative length of the projection
# of each point onto each line
a = np.diff(lines)
b = points[:,:,None] - L1[:,None,:]
print(a.shape)
print(b.shape)
[rows, cols, pages] = np.shape(b)
Z = np.zeros((cols, pages))
for k in range(cols):
for l in range(pages):
Z[k][l] = a[0][l]*b[0][k][l] + a[1][l]*b[1][k][l]
N = np.linalg.norm(a, axis=0)**2
relativeProjectionLength = np.squeeze(np.asarray(Z/N))
在此示例中,a 和 b 的前两个维度表示我需要用于点积的 x 和 y 坐标。 a的形状是(2,7),b的形状是(2,6,7)。由于点积减少了第一个维度,我希望结果是形状 (6,7)。如果没有慢速循环,我该如何计算?
我尝试过的:
我认为正确广播的 numpy.dot 可以完成这项工作,但是我无法正确设置尺寸。
a = a[:, None, :]
Z = np.dot(a,b)
这给了我以下错误:
形状 (2,1,7) 和 (2,6,7) 未对齐:7 (dim 2) != 6 (dim 1)
【问题讨论】:
-
与
+和*等元素明智操作一起使用的广播不适用于np.dot。它有自己的坐标轴匹配规则。