我有scipy.brute的问题,我以这种方式设置了最大化
import numpy as np
from scipy.optimize import brute
from scipy.optimize import fmin
from scipy.stats import norm
lambmarket=np.array([1.1076, 0.0615, 0.15238, 0.16265, 0.1761301, 0.193762, 0.0778772, 0.079162, 0.07505194, 0.071973])
xnew = np.array([0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0, 20.0, 30.0])
def optimization(key):
if key=='inc':
ranges=slice(0,2,0.2), slice(0.001,2.998,0.5)
finalB =brute(incmse, ranges, full_output=True,finish=None, disp=True)
finalA=fmin(incmse, finalB[0], xtol=0.001, ftol=0.001, maxiter=500, maxfun=500)
return finalA
,其中
def incmse(*p):
v, sigma =p[0]
print v,sigma
msqdiff=[(( lambmarket[t] - s_t(0.,xnew[t], v, 0.003, sigma) )**2) for t in range(0,len(xnew))]
print sum(msqdiff)
return msqdiff
def s_t(t,T,v,r,sigma):
m=r-0.5*sigma**2
gamma=1+2*m/(sigma**2)
nu=m+sigma**2
delta=m-gamma*sigma**2
beta=-m*gamma+(gamma**2)*(sigma**2)/2
s = lambda t,T,v: norm.cdf((-v-m*(T-t))/(sigma*np.sqrt(T-t))) - np.exp(v+r*(T-t)) * norm.cdf((-v-nu*(T-t))/(sigma*np.sqrt(T-t))) \
+ np.exp(( 1-gamma )*v)/gamma * norm.cdf((m*(T-t)-v)/(sigma*np.sqrt(T-t))) \
- np.exp(v+(T-t)*beta)/gamma * norm.cdf((delta*(T-t)-v)/(sigma* np.sqrt(T-t)))
lamb = ((1/0.01) * (s(t,T+0.01,v)-s(t,T,v)))/(1-s(t,T,v))
return lamb
可以通过
执行 optimization('inc')
(lambmarket和xnew是全球性的) 从印刷品中我知道错误发生在所有蛮力迭代完成之后......是否有人可以解释我?
(我寻找类似的主题并尝试自己解决,但我仍然无法理解问题所在)
完整错误输出
param=optimization(key)
File "/home/myway/calibration.py", line 129, in optimization
finalB =brute(incmse, ranges, full_output=True,finish=None, disp=True)
File "/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 2542, in brute
Jout = vecfunc(*grid)
File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 1573, in __call__
return self._vectorize_call(func=func, args=vargs)
File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 1643, in _vectorize_call
copy=False, subok=True, dtype=otypes[0])
ValueError: setting an array element with a sequence.
答案 0 :(得分:2)
正如cel所指出的,问题只是我(不友好)返回一个向量而不是单个值,函数 incmse 必须修改如下
def incmse(*p):
v, sigma =p[0]
print v,sigma
msqdiff=[(( lambmarket[t] - s_t(0.,xnew[t], v, 0.003, sigma) )**2) for t in range(0,len(xnew))]
print sum(msqdiff)
return sum(msqdiff)
现在根据需要将单个值传递给scipy.optimize.brute。