看板 Python 關於我們 聯絡資訊
※ 引述《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://www.ptt.cc/bbs/Python/M.1454179101.A.DE4.html
horby: 謝謝,問題順利解決了。 02/02 20:01