运筹系列36:cvxpy与pytorch结合

1. 背景

这里是官方地址:https://github.com/cvxgrp/cvxpylayers
使用场景:
在这里插入图片描述
安装:pip install cvxpylayers

2. 例子

import cvxpy as cp
import torch 
from cvxpylayers.torch import CvxpyLayer

n, m = 2, 3
x = cp.Variable(n)
A = cp.Parameter((m, n))
b = cp.Parameter(m)
constraints = [x >= 0]
objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
problem = cp.Problem(objective, constraints)
assert problem.is_dpp()

cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
A_tch = torch.randn(m, n, requires_grad=True)
b_tch = torch.randn(m, requires_grad=True)

# solve the problem
solution, = cvxpylayer(A_tch, b_tch)

# compute the gradient of the sum of the solution with respect to A, b
solution.sum().backward()

在这个问题中,损失函数为||Ax-b||/2(x≥0),需要求解的参数为x,传递的训练数据为A和b(torch的格式)。

猜你喜欢

转载自blog.csdn.net/kittyzc/article/details/105987354