Python numpy在不同的行上执行相同的操作

Python numpy在不同的行上执行相同的操作,python,numpy,cython,Python,Numpy,Cython,假设我有一个如下列表: points = np.array( [ . . . ] , [ . . .], [ . . .] ) # shape is (500000, 1000) norm = np.linalg.norm(points - target, axis=1) 另一份名单是 target = np.array([ . . .]) #shape is (1000,) 现在我可以计算L2范数,如下所示: points = np.array( [ . . . ] , [ . .

假设我有一个如下列表:

points = np.array( [ . . . ] , [ . . .], [ . . .] )  # shape is (500000, 1000)
norm = np.linalg.norm(points - target, axis=1)
另一份名单是

target = np.array([ . . .])  #shape is (1000,)
现在我可以计算L2范数,如下所示:

points = np.array( [ . . . ] , [ . . .], [ . . .] )  # shape is (500000, 1000)
norm = np.linalg.norm(points - target, axis=1)
这工作得很好,但当我想要执行100K目标值时,速度非常慢。目前,我从目标列表中获得一个目标值,并计算每个目标的范数

有没有快速的方法可以做到这一点?

是的,广播

deltas = points[:, None, :] - targets[None, :, :]  # shape (n_points, n_targets, n_dims)
norm = np.linalg.norm(deltas, axis=2)  # shape (n_points, n_targets)
但是,如果您有500k点、100k目标和1000-D(即500000*100000*1000*8B=400 TB您需要的RAM),则可能会耗尽所有内存


很可能是由于所有计算的实际成本,而不是使用Python循环造成的。考虑使用GPU计算(也许TeaNo)来加速你需要的东西。

500000×1000是很多元素。500k*100k甚至更多。对于64位数字,500k*1k元素已经接近4GB。使用500k*100k元素,可能会耗尽内存。也许你可以试着用类似的东西?另一个可能有用的链接。最后一句话是否意味着你在
norm
计算的基础上进行迭代?如果是,请显示该代码。否则,答案将集中在内存大小上。