我不知道为什么这个问题,一直是参数的变量超出范围,现在也问题是代码并给我这个'Bounds'类型的eroor对象没有len():
(我希望我能在代码中找到错误或找到使用变量边界的其他好代码)
Traceback (most recent call last):
File "./trigger_SLQ.py", line 160, in <module>
main()
File "./trigger_SLQ.py", line 156, in main
opt(x0)
File "./trigger_SLQ.py", line 148, in opt
res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs, T=10000.0,
stepsize=1.0, niter=100, niter_success=200, accept_test=bounds)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
611, in basinhopping
accept_tests, disp=disp)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
72, in __init__
minres = minimizer(self.x)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
280, in __call__
return self.minimizer(self.func, x0, **self.kwargs)
File "/usr/lib/python3/dist-packages/scipy/optimize/_minimize.py", line 455,
in minimize
constraints, callback=callback, **options)
File "/usr/lib/python3/dist-packages/scipy/optimize/slsqp.py", line 329, in
_minimize_slsqp
if bounds is None or len(bounds) == 0:
TypeError: object of type 'Bounds' has no len()
b0 = (5, 95)
b1 = (0.10, 0.95)
b2= (2, 8)
bounds=((5, 95), (0.10, 0.95), (2, 8))
class Bounds(object):
def __init__(self, xmax=[0,0,2], xmin=[100,0.100,8], stepsize=0.01):
self.xmax = np.array(xmax)
self.xmin = np.array(xmin)
self.stepsize = stepsize
def __call__(self, x):
min_step = np.maximum(self.xmin - x, -self.stepsize)
max_step = np.minimum(self.xmax - x, self.stepsize)
random_step = np.random.uniform(low=min_step, high=max_step, size=x.shape)
xnew = x + random_step
return xnew
bounded_step = Bounds(np.array([b[0] for b in bounds]), np.array([b[1]
for b in bounds]), np.array([b[2] for b in bounds]))
def opt(x0):
bounds = Bounds()
minimizer_kwargs = {'method':'SLSQP', 'bounds':bounds,'options':{'maxiter':1000, 'ftol':1e-2, 'eps':1e-2},}
res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs, T=10000.0, stepsize=1.0, niter=100, niter_success=200, accept_test=mybounds)
print(res.x)
return res.x
def main():
x0 = np.array((50.0, 0.50, 5.0)) # initial guess
opt(x0)
if __name__ == "__main__":
main()