使用 numpy 进行更快的详尽研究

Faster exhaustive research using numpy

我正在尝试使用详尽的研究来最大化两个函数之间的最小值,此解决方案有效但 python 中的循环消耗了大量计算时间。有没有一种有效的方法可以使用 numpy(网格或矢量化)来解决这个问题?

代码:

穷举研究方法中使用了以下函数

import numpy as np

def F1(x):
  return (x/11)**10

def F2(x,y,z):
  return z+x/y

def F3(x,y,z,a,b,c):
  return ((x+y)**z)/((a-b)**c)

详尽的研究方法采用 6 个参数(标量或一维数组)。目前我只想在标量上计算我的代码,然后我可以使用另一个函数来浏览那些参数,如果它们是一维数组。

def B_F(P1, P2, P3,P4, P5, P6) :
  # initializing my optimal parameters 
  a_Opt, b_opt, c_opt, obj_opt = 0, 0, 0, 0 
  # feasible set
  a = np.linspace(0.0,1.0,10)
  b = np.linspace(0.0,100.0,100)  
  c = np.linspace(0.0,100.0,100)  
       
  for i in a:
      for j in b:
        for k in c:
          #if constraint is respected
          if P1*k+P2*j+2*(i*k*j) <= F1(P3):
              # calculate the max min of the two function
              f_1 = F2(i,k,P6)
              f_2 = F3(i,k,j,10,P4,P5)
              min_f = np.minimum(f_1, f_2)
              # extract optimal parameters and objective function
              if obj_opt <= min_f :
                  a_Opt = i 
                  b_opt = j
                  c_opt = k 
                  obj_opt = min_f

  exhaustive_research = np.array([[obj_opt, a_Opt, b_opt, c_opt]])          
  
  return  exhaustive_research

你可以这样做:

A,B,C = np.meshgrid(a,b,c)
mask = P1*C+P2*B+2*(A*B*C) <= F1(P3)
A = A[mask]
B = B[mask]
C = C[mask]
  
f_1 = F2(A,C,P6)
f_2 = F3(A,C,B,10,P4,P5)
min_f = np.minimum(f_1, f_2)
ind = np.argmax(min_f)
obj_opt, a_Opt, b_opt, c_opt = min_f[ind], A[ind], B[ind], C[ind]