【问题标题】:Increase speed of numpy operations on large number of vectors提高对大量向量的 numpy 操作的速度
【发布时间】:2020-07-21 16:03:18
【问题描述】:

我想要更快地实现如下所示的功能。理想情况下,当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)

【问题讨论】:

    标签: python arrays vectorization numpy-ndarray numpy-einsum


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 这些函数是高效的,因为它们是在a backend written in C 中实现的,而 Python 只是执行它。后端使用SIMD operations对多个数据执行相同的操作,而不是迭代加载每个数据进行操作。
      猜你喜欢
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多