在 numpy/scipy 中向量化 for 循环?

5 python optimization numpy vectorization scipy

我正在尝试矢量化我在类方法中的 for 循环。for 循环具有以下形式:它遍历一堆点并根据某个变量(以下称为“self.condition_met”)是否为真,在该点上调用一对函数,并将结果添加到列表中. 这里的每个点都是列表向量中的一个元素,即看起来像 array([[1,2,3], [4,5,6], ...]) 的数据结构。这是有问题的函数:

def myClass:
   def my_inefficient_method(self):
       final_vector = []
       # Assume 'my_vector' and 'my_other_vector' are defined numpy arrays
       for point in all_points:
         if not self.condition_met:
             a = self.my_func1(point, my_vector)
             b = self.my_func2(point, my_other_vector)
         else:
             a = self.my_func3(point, my_vector)
             b = self.my_func4(point, my_other_vector)
         c = a + b
         final_vector.append(c)
       # Choose random element from resulting vector 'final_vector'
Run Code Online (Sandbox Code Playgroud)

self.condition_met 是在调用 my_inefficient_method 之前设置的,因此似乎没有必要每次都检查它,但我不确定如何更好地编写它。由于这里没有破坏性操作,似乎我可以将整个内容重写为矢量化操作——这可能吗?任何想法如何做到这一点?

mtr*_*trw 2

你能重写my_funcx为矢量化吗?如果是这样,你可以这样做

def myClass:
   def my_efficient_method(self):
       # Assume 'all_points', 'my_vector' and 'my_other_vector' are defined numpy arrays
       if not self.condition_met:
           a = self.my_func1(all_points, my_vector)
           b = self.my_func2(all_points, my_other_vector)
       else:
           a = self.my_func3(all_points, my_vector)
           b = self.my_func4(all_points, my_other_vector)
       final_vector = a + b
       # Choose random element from resulting vector 'final_vector'
Run Code Online (Sandbox Code Playgroud)