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