scipyinimize 函数中多限制条件的问题


par_0 = np.array([5, 0.1, 0.1])
w = par_0[0:2].reshape((-1,1))
b = par_0[-1]


def primal_L(params):
    w = params[0:2].reshape((-1,1))
    return 0.5 * np.dot(w.T, w)


cons_temp = []
for i in range(y_train.shape[0]):
    cons_temp.append({
        'type' : 'ineq',
        'fun': lambda x: y_train[i] * (np.dot(X_test[i], x[0:2].reshape((-1, 1))) + x[-1]) - 1,
        'args': ()
    })            #这里添加了300个限制条件,但是args后面应该填什么呢


res = minimize(primal_L, par_0, constraints=cons)
print(res)

[ a>1 , 1<b<2 , 1< k < b, ... ]  三百个条件,直接用all() 函数判断

把你的参数加到lambda函数作为匿名函数的参数,这样约束条件才生效。同时写到'args': ()内,表明是你自己的参数。
看代码样子i是你的300个限制条件变化的参数,可以这么写:

cons_temp = []
for i in range(y_train.shape[0]):
cons_temp.append({
'type' : 'ineq',
'fun': lambda x, i: y_train[i] * (np.dot(X_test[i], x[0:2].reshape((-1, 1))) + x[-1]) - 1,
'args': (i)
})