【问题标题】:Faster exhaustive research using numpy使用 numpy 进行更快的详尽研究
【发布时间】:2021-07-03 00:34:10
【问题描述】:

我试图通过详尽的研究来最大化两个函数之间的最小值,这个解决方案有效,但 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

【问题讨论】:

  • 我不认为if P1*k+P2*j+2*(i*k*j) &lt;= F1(P3): 对一维数组有效...
  • 另外请正确格式化您的代码...并提供minimal reproducible example
  • 您是否意识到您正在尝试计算 10**11 个值?你认为你有足够的内存来存储这么大的网格吗?
  • 我使用另一个函数来浏览一维数组,现在我只想计算它的标量
  • 感谢您的重播。我可以计算少于10**1110**4.. 它可以与我的RAM 一起使用

标签: python python-3.x optimization parallel-processing brute-force


【解决方案1】:

你可以这样做:

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]

【讨论】:

  • 非常感谢您的回答。最后你的意思是 c[ind] 还是 C[ind]?如果 P1, P2, P3... 是一维数组,是否可以用同样的方法求解?
  • C[ind] 不是c[ind],抱歉打错了,已更正。如果 th Ps 是数组,不确定你想做什么,因为正如我所说,if P1*k+P2*j+2*(i*k*j) &lt;= F1(P3): 会抛出......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多