作者yogi (Yogi)
看板Python
标题Re: [问题] Scipy 极大化限制式写法求解
时间Sun Jan 31 02:38:18 2016
※ 引述《horby (horby)》之铭言:
: 想请教关於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要怎麽写,
: 请大家指点一下,谢谢!!!
照说明文件的解释
constraints 应该要先写成 g_i(x) >= 0 的型式
所以如果你有某个 i - 0.1 <= g(x) <= i + 0.1
应该先做些小小的推导 把这个写成两条不等式:
g(x) - i + 0.1 >= 0
i + 0.1 - g(x) >= 0
然後把这两条不等号左边放进constrains中:
cons = ({'type': 'ineq', 'fun': lambda x: ......},
{'type': 'ineq', 'fun': lambda x: ......})
这样子...
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.160.165.64
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1454179101.A.DE4.html
1F:推 horby: 谢谢,问题顺利解决了。 02/02 20:01