提高对大量向量进行 numpy 运算的速度

Increase speed of numpy operations on large number of vectors

我想要更快地实现下面显示的功能。理想情况下,当 number_points 变量设置为 400-500 时,代码应该可以工作。有什么方法可以改进函数定义以提高速度(参见示例 运行)?

这是我的代码:

import numpy as np
import time

def initialize_plane_points(Domain = 100,number_points=200,Plane_Offset=0.0):
    '''Domain has implied coordinates of mm and the number of 
    points represents the number of samples within that space.  '''
    X = np.linspace(-Domain,Domain,number_points)
    #print(X)
    Y = np.linspace(-Domain,Domain,number_points)
    #print(Y)
    ZZ = np.array([])
    XX,YY = np.meshgrid(X,Y)
    for x in XX:
        for y in YY:
            ZZ = np.append(ZZ,[Plane_Offset])
    ZZ = np.reshape(ZZ, (len(XX),len(YY)))
    
    Shape = np.array([])
    for i in range(len(XX)):
        for j in range(len(YY)):
            Shape = np.append(Shape,[XX[i,j],YY[i,j],ZZ[i,j]])
    a = int(len(Shape) / 3)
    SHAPE = np.reshape(Shape,(a,3))
    return SHAPE



T0 = time.perf_counter()
Points = initialize_plane_points(number_points=100)
T1 = time.perf_counter()
    
    print("100 initialize time: ",T1-T0)

作为一般规则,如果您想要使用 numpy 的高效代码,您需要尽可能少的循环迭代。

np.appendas也比较慢。相反,尝试使用矢量代数构建数组。例如,ZZ = np.ones((len(XX),len(YY)) * Plane_Offset 将比您拥有的两个嵌套循环快得多。

New Results for array generation 该函数被重写,避免了任何显式的 for 循环。时间上的差异是惊人的。我很想知道这些功能是如何如此高效的。

def initialize_plane_points_2(Domain = 100,number_points=200,Plane_Offset=0.0):
    X = np.linspace(-Domain,Domain,number_points)
    Y = np.linspace(-Domain,Domain,number_points)
    
    XX,YY = np.meshgrid(X,Y)
    ZZ = np.ones((len(XX),len(YY)))*Plane_Offset
    #print(ZZ.shape, XX.shape,YY.shape)
    
    Shape = np.dstack((XX,YY,ZZ)).reshape(-1,3)
    return Shape