楼主:
horby (horby)
2016-01-29 00:23:57想请教关于scipy限制式的写法
简单程式如下:
import numpy as np
import scipy as sp
import scipy.optimize as opt
#给定一些变量值,w0是起始值,w1是限制的依据,score是其他运算资料,不重要
w1 = np.array([ 0.4, 0.3, 0.2, 0.1, 0. , -0.1, -0.2, -0.3, -0.4])
w0 = np.ones(w1.size)/w1.size
score = np.array([ 0.04, -0.24, 0.01, 0. , -0.27, 0.02, 0.03, -0.11, -0.05])
#目标函数
def objfun(w, score, w1):
return -1.0 * np.dot(w, score)
#限制式
bounds = [(-0.1 + i, i+0.1) for i in w1]
#求解
results = opt.minimize(objfun, w0, args = (score, w1),
method = "SLSQP",
bounds = bounds)
基本上我要求解w使函数极大化,但是w的变化范围限定在w1的正负10%
上述的写法可以成功,但我想知道以constraints改写bounds要怎么写,
请大家指点一下,谢谢!!!