加速scipy最小化

2024-10-02 18:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在scipy中有一个最小方差优化问题,还有一个附加约束:

def min_variance_scipy(initial_point: np.array, 
                       covariance_matrix: np.array):
    start = time.time()
    n = covariance_matrix.shape[0]
    
    objective_function = lambda w, c: 1000 * w.dot(c).dot(w)
    A = np.array([[1] * n])
    ub = [1]
    lb = [1]
    bounds = Bounds([0] * n, [1] * n)
    diversification_target = {
        'type': 'ineq',
        'fun': lambda weights: (2 / n) - np.sum(weights**2)
    }
    constraints = [LinearConstraint(A, lb, ub), diversification_target]
    
    solution = minimize(fun=objective_function,
                        x0=initial_point,
                        method='trust-constr',
                        bounds=bounds,
                        constraints=constraints,
                        args=(covariance_matrix,),
                        tol=1e-6,
                        jac=lambda x, c: 2000 * x.T.dot(c.T),
                        hess=lambda x, c: 2000 * c.T,
                        options={'gtol': 1e-6})
                        # options={'verbose': 3, 'finite_diff_rel_step': 1e-5,})
     
    return solution.x

如果我使用以下选项运行此优化器:

initial_point: np.array of shape == (600, ).
covariance_matrix: matrix of shape == (600, 600)

执行时间为+100秒。我想加快这场演出。我测试了cvxpy,但是如果我们使用DCCP优化器,有些约束不是DCP或DCCP。(我有更多的限制要测试)

我还将方法参数更改为SLSQP,但没有满足diversification_target约束


Tags: lambdatargettimenpscipyarraymatrixdot