问题
In the following script:
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})
I am trying to optimise for x but I am having the following message:
Warning: Maximum number of function evaluations has been exceeded.
And the result is:
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?
回答1:
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: 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.
Result for your example:
>>> 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
回答2:
Modifying the proposal of FuzzyDuck, I replace sm +=((b-a)**2) which return me the desired result.
来源:https://stackoverflow.com/questions/29229810/optimisation-using-scipy