简单介绍
目前,python中的CVX宏包有 CVXPY 和 CVXOPT 两大类。
从官方文档来看:
CVXOPT is a free software package for convex optimization based on the Python programming language. It can be used with the interactive Python interpreter, on the command line by executing Python scripts, or integrated in other software via Python extension modules. Its main purpose is to make the development of software for convex optimization applications straightforward by building on Python’s extensive standard library and on the strengths of Python as a high-level programming language.
via: https://cvxopt.org/
CVXPY is a Python-embedded modeling language for convex optimization problems. It allows you to express your problem in a natural way that follows the math, rather than in the restrictive standard form required by solvers.
via: https://www.cvxpy.org/
简单来说,
COVOPT是能够解决线性规划和二次型规划问题,其应用场景如机器学习中的SVM算法中的Hard Margin SVM情形;
CVXPY是一种可以内置于Python中的模型编程语言,解决凸优化问题。
宏包安装
本文基于windows系统进行说明,安装过程主要可分为以下几个步骤:
- 相关依赖模块的更新;
- 宏包的下载与安装;
- 测试;
上述两个宏包的安装步骤类似,下面以CVXPY为例进行详细说明。
相关依赖模块的更新
简单起见,直接更新所有安装模块。
cmd玩家:
-
查询所有需更新的包
# pip list --outdated
-
升级包
若需要更新的包比较少的话可以直接使用pip命令:# pip install --upgrade 更新包名
为了提升下载速度和安装成功率,也可以使用镜像,比如:
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade 更新包名
但是一般来说要更新的库都会比较多,所以我们可以通过代码进行批量更新:
import pip
from subprocess import call
from pip._internal.utils.misc import get_installed_distributions
for dist in get_installed_distributions():
call("pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade " + dist.project_name, shell=True)
Anaconda玩家:
-
首先打开Anaconda Prompt,在更新包之前,可以先更新一下 Anaconda 本体(当然也可以不更新)。输入以下命令:
# conda update conda
-
升级所有包
# conda update --all
宏包的下载与安装
cmd玩家:
-
自动玩法:
# pip install cvxpy
-
手动玩法:
根据操作系统和python版本选择下载相应的.whl文件
下载指路:请往此处.
安装:# python -m pip install .whl文件位置
Anaconda玩家:
-
自动玩法:(概率掉落不知名错误)
I. 创建新的conda环境:# conda create --name cvxpy # conda activate cvxpy
当然,也可以直接active一个现存的环境了(不嫌乱的话)。
II. 下载cvxpy:
# conda install -c conda-forge cvxpy
-
手动玩法:
与cmd玩家类似,根据操作系统和python版本选择下载相应的.whl文件
下载指路:请往此处.
开始安装:# pip install .whl文件位置
测试
cmd玩家:
-
自动玩法:
# pip install pytest # pytest cvxpy/tests
-
手动玩法:
请随意开发尝试。:)
也可使用官方demo:
import cvxpy as cp
import numpy as np
# Generate data.
m = 20
n = 15
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
# Define and solve the CVXPY problem.
x = cp.Variable(n)
cost = cp.sum_squares(A @ x - b)
prob = cp.Problem(cp.Minimize(cost))
prob.solve()
# Print result.
print("\nThe optimal value is", prob.value)
print("The optimal x is")
print(x.value)
print("The norm of the residual is ", cp.norm(A @ x - b, p=2).value)
Anaconda玩家:
-
自动玩法:
# conda install pytest # pytest cvxpy/tests
-
手动玩法:
同上。
Good Luck!