Skip to main content
 首页 » 编程设计

python之如何编写与 scipy.optimize.minimize() 一起使用的多元目标函数,以便它也可以用 matplotlib 绘制

2024年10月25日7shanyou

我有一个函数,我想为其找到一个全局最大值。写成 python 函数,它看起来像这样:

def fh(x,sign=1.0): 
    x1 = x[0,:] 
    x2 = x[1,:] 
    out = (np.sin(x1 - x2/8)**2 + np.sin(x2 + x1/8)**2)/(np.sqrt((x1 - 8.6998)**2 + (x2 - 6.7665)**2) + 1) 
    return out 

它的编写(在 this answer 的帮助下)使得使用以下代码很容易绘制:

import numpy as np 
import matplotlib.pyplot as mplot 
import matplotlib.cm as cm 
from mpl_toolkits.mplot3d import Axes3D as m3d 
 
x = np.linspace(-20,30,num=250) 
y = x 
dim = np.size(x) 
 
xx = np.zeros((2,dim,dim)) 
 
xx[0],xx[1] = np.meshgrid(x,y) 
 
zz = fh(xx) 
 
fig = mplot.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
ax.plot_surface(xx[0,:],xx[1,:],zz,cmap=cm.coolwarm) 

问题是 scipy.optimize.minimize() 不能使用这个函数,因为它传递一个形状为 (n,) 的向量给它.结果报错:

<ipython-input-25-2e1bca04325c> in fh(x, sign) 
      2  
      3 def fh(x,sign=1.0): 
----> 4     x1 = x[0,:] 
      5     x2 = x[1,:] 
      6     out = (np.sin(x1 - x2/8)**2 + np.sin(x2 + x1/8)**2)/(np.sqrt((x1 - 8.6998)**2 + (x2 - 6.7665)**2) + 1) 
 
IndexError: too many indices 

解决此问题的一种方法是在目标函数中使用条件条件在引用输入之前检查输入的大小,但这让我觉得丑陋且效率不高。

还有其他方法吗?

请您参考如下方法:

使用广播(参见此处的示例 http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)。

在您的情况下,将函数更改为

def fh(x,sign=1.0): 
    x1 = x[0]  # changed 
    x2 = x[1]  # changed 
    out = (np.sin(x1 - x2/8)**2 + np.sin(x2 + x1/8)**2)/(np.sqrt((x1 - 8.6998)**2 + (x2 - 6.7665)**2) + 1) 
    return out 

将适用于形状 (2,) 和 (2,n) 的输入,即最小化和绘图。