我有一个函数,我想找到它的全局最大值。写成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) 的输入,即最小化和绘图。
关于python - 如何编写与 scipy.optimize.minimize() 一起使用的多变量目标函数,以便也可以使用 matplotlib 绘制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045848/