使用scipy进行优化 [英] Optimisation using scipy
问题描述
在以下脚本中:
import numpy as np
from scipy.optimize import minimise
a=np.array(range(4))
b=np.array(range(4,8))
def sm(x,a,b):
sm=np.zeros(1)
a=a*np.exp(x)
sm += sum(b-a)
return sm
x0=np.zeros(4)
print sm(x0,a,b) #checking my function
opt = minimize(sm,x0,args=(a,b),method='nelder-mead',
options={'xtol': 1e-8, 'disp': True})
我正在尝试针对x进行优化,但是我收到以下消息:
I am trying to optimise for x but I am having the following message:
警告:超过了功能评估的最大数量.
Warning: Maximum number of function evaluations has been exceeded.
结果是:
array([-524.92769674,276.6657959,185.98604937,729.5822923])
array([-524.92769674, 276.6657959 , 185.98604937, 729.5822923 ])
这不是最佳选择. 我的问题是我是否收到此消息和结果,因为起点不正确?
Which is not the optimal. My question is am I having this message and result because my starting points are not correct?
推荐答案
您的函数sm
似乎是不受限制的.随着x
的增加,sm
的负值将变得越来越大,因此,它会降到-inf
.
Your function sm
appears to be unbounded. As you increase x
, sm
will get ever more negative, hence the fact that it is going to -inf
.
Re:注释-如果要使sm()
尽可能接近零,请修改函数定义的最后一行以读取return abs(sm)
.
Re: comment - if you want to make sm()
as close to zero as possible, modify the last line in your function definition to read return abs(sm)
.
这使函数的绝对值最小化,使其接近零.
This minimised the absolute value of the function, bringing it close to zero.
您的示例结果:
>>> opt = minimize(sm,x0,args=(a,b),method='nelder-mead', options={'xtol': 1e-8, 'disp': True})
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 153
Function evaluations: 272
>>> opt
status: 0
nfev: 272
success: True
fun: 2.8573836630130245e-09
x: array([-1.24676625, 0.65786454, 0.44383101, 1.73177358])
message: 'Optimization terminated successfully.'
nit: 153
这篇关于使用scipy进行优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!