尺寸与 numpy 广播不匹配

Dimension mismatch with numpy broadcasting

我在使用 numpy 广播时遇到问题。当我尝试进行矩阵-矩阵乘法时,出现以下错误:

"operands could not be broadcast together with shapes (2,6) (2,7)"

这是不会的代码 运行:

import numpy as np

pointsX = np.array([0.5, 2, 3, 5.5, 8, 11])
pointsY = np.array([1, 2, -1.5, 0.5, 4, 5])
points = np.asarray([pointsX, pointsY])

linesX = np.array([0, 2, 4, 6, 10, 10, 0, 0])
linesY = np.array([0, 0, 0, 0, 0, 4, 4, 0])
lines = np.asarray([linesX, linesY])

x1 = linesX[0:-1]
y1 = linesY[0:-1]
L1 = np.asarray([x1, y1])

# calculate the relative length of the projection
# of each point onto each line
a = [np.diff(pointsX), np.diff(pointsY)]
b = points - L1
relativeProjectionLength = np.dot(a, b)/np.linalg.norm(b)

当我尝试计算 b 时出现问题。我希望它是一个 [2x6x7] 矩阵。我如何执行此操作?我可以用循环尝试它,但实际数据会非常大(~10000 点和~10000 行)并且必须是高性能的。

我读到有关扩展其中一个运算符(点或 L1)的维度,但以下代码也没有解决问题:

b = points - L1[:,:,None]
b = points[:,:,None] - L1

感谢任何帮助。

您需要将两者都扩展到 3D,保持第一个轴对齐并沿最后一个轴引入新轴 points,第二个轴沿最后一个轴引入 L1,然后减去 -

points[:,:,None] - L1[:,None,:] # or points[...,None] - L1[:,None]