优化函数scipy.optimize

时间:2013-11-18 14:54:07

标签: python numpy scipy

我是python和统计编程的新手。对于课堂作业,我们被要求实施python套索L1回归。 这涉及使用QP求解器来解决。

0.5 *(x^t * H * x) + f^t * H
st x > 0 (every element of x is greater than zero)

这些是块向量和矩阵。我使用2维数组用于向量,使用四维数组用于矩阵H

def function(x):
    x = x.reshape(2, -1)
    return 0.5*np.tensordot(x,(np.tensordot(H,x,([1,3],[0,1]))),([0,1],[0,1])) + np.tensordot(f,x,([0,1],[0,1]))

initial_val = np.random.randn(2 * (k+1)).reshape((2,k+1))

bnds = (0,None)
theta = scipy.optimize.minimize(function, initial_val, method="SLSQP", bounds=bnds)

但我仍然在theta.x向量中获得负值。谁能告诉我哪里出错?

1 个答案:

答案 0 :(得分:1)

如果优化标量函数,则需要为优化提供约束:

scipy.optimize.minimize(
    function,
    initial_val,
    method="SLSQP",
    bounds=bnds,
    constraints = [{'type':'ineq', 'fun':lambda x: x}])

或用于矢量函数:

constraints = [{'type':'ineq', 'fun':lambda x: x[i]} \
                   for i in range(len(initial_val))]

请注意,如果它是一个向量,那么您还需要为每个元素提供边界:

 bnds = [(0, None) for _ in range(len(initial_val))]

您可能还想查看reference

相关问题