1
我試圖通過在scipy中使用最小化函數來找到我的模型的優化權重值。如下面的代碼所示,我定義了我的錯誤函數,返回模型的一個減去f1分數。L-BFGS-B不滿足給定的約束
def err_func(weights,x,y):
undetected=0
correct=0
incorrect=0
results=fun(weights,x)
for i in range(0,len(results)):
if(results[i]==y[i]):
correct+=1
elif(not (results[i]==y[i])):
incorrect+=1
undetected=len(y)-(correct+incorrect)
precision=float(correct)/float(correct + incorrect)
recall=float(correct)/float(correct + incorrect + undetected)
f1=2 * precision * recall/(precision + recall)
return 1.0-f1
我使用約束條件,每個值的權重介於零和一,權重的總和等於一。這些定義如下:
cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)})
bnds = tuple((0.0, 1.0) for x in weights)
eps=1e-2
但運行minimze方法,同時,我的功能不滿足約束。
from scipy.optimize import minimize
res = minimize(err_func, weights,method='L-BFGS-B', args=(x,y),constraints=cons,bounds=bnds,options = {'eps':eps,'maxiter':100})
print res
test_weights=res.x
print sum(test_weights)
我得到了這樣的輸出,權重總和大於1。我錯過了什麼?
> fun: 0.4955555555555555 hess_inv: <11x11 LbfgsInvHessProduct with
> dtype=float64>
> jac: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) message: 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
> nfev: 24
> nit: 1 status: 0 success: True
> x: array([ 0. , 0.22222222, 0. , 1. , 1. ,
> 0.11111111, 1. , 1. , 1. , 0. , 1. ])
> 6.33333333333