Python二次规划和线性规划使用实例
作者:yaominghui 时间:2023-08-28 05:37:10
这篇文章主要介绍了Python二次规划和线性规划使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
对于二次规划(quadratic programming)和线性规划(Linear Programming)问题
MATLAB里是有quadprog函数可以直接用来解决二次规划问题的,linprog函数来解决线性规划问题。Python中也有很多库用来解决,对于二次规划有CVXOPT, CVXPY, Gurobi, MOSEK, qpOASES 和 quadprog; 对于线性规划有Gurobi,PuLP, cvxopt。
目前发现quadprog进行pip install quadprog不成功,而cvxopt成功了,就先说cvxopt的使用。
安装
conda install -c conda-forge cvxopt
安装非常顺利
使用
cvxopt有自己的matrix格式,因此使用前得包装一下
对于二次规划:
def cvxopt_solve_qp(P, q, G=None, h=None, A=None, b=None):
P = .5 * (P + P.T) # make sure P is symmetric
args = [cvxopt.matrix(P), cvxopt.matrix(q)]
if G is not None:
args.extend([cvxopt.matrix(G), cvxopt.matrix(h)])
if A is not None:
args.extend([cvxopt.matrix(A), cvxopt.matrix(b)])
sol = cvxopt.solvers.qp(*args)
if 'optimal' not in sol['status']:
return None
return np.array(sol['x']).reshape((P.shape[1],))
对于线性规划:
def cvxopt_solve_lp(f, A, b):
#args = [cvxopt.matrix(f), cvxopt.matrix(A), cvxopt.matrix(b)]
#cvxopt.solvers.lp(*args)
sol = cvxopt.solvers.lp(cvxopt.matrix(f), cvxopt.matrix(A), cvxopt.matrix(b))
return np.array(sol['x']).reshape((f.shape[0],))
参考:
Quadratic Programming in Python
Linear Programming in Python with CVXOPT
cvxopt.org
标签:Python,二次,线性,规划
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)
2022-08-25 05:19:38
python DataFrame数据格式化(设置小数位数,百分比,千分位分隔符)
2021-02-03 21:34:10
![](https://img.aspxhome.com/file/2023/1/68921_0s.png)
Python中用字符串调用函数或方法示例代码
2023-03-05 15:37:59
一篇文章让你搞清楚JavaScript事件循环
2024-04-19 09:53:02
![](https://img.aspxhome.com/file/2023/5/136045_0s.png)
Python把csv数据写入list和字典类型的变量脚本方法
2021-05-27 22:04:20
Python torch.flatten()函数案例详解
2022-11-11 16:04:27
Asp函数介紹(37个常用函数)
2011-04-11 11:06:00
django初始化数据库的实例
2023-09-19 07:35:47
python绘制堆叠条形图介绍
2021-07-01 23:12:36
![](https://img.aspxhome.com/file/2023/6/112516_0s.jpg)
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
2023-04-21 19:20:50
![](https://img.aspxhome.com/file/2023/1/109951_0s.gif)
详解Python中list[::-1]的几种用法
2021-10-12 23:51:40
全面分析MySQL ERROR 1045出现的原因及解决
2024-01-19 08:55:41
![](https://img.aspxhome.com/file/2023/0/75560_0s.jpg)
Golang 限流器的使用和实现示例
2024-04-25 15:06:25
Python Process多进程实现过程
2021-04-30 02:21:45
![](https://img.aspxhome.com/file/2023/4/85384_0s.png)
MySQL IFNULL判空问题解决方案
2024-01-21 13:23:10
JavaScript中两个字符串的匹配
2023-08-08 00:46:01
python 管理系统实现mysql交互的示例代码
2024-01-28 16:30:52
![](https://img.aspxhome.com/file/2023/8/108038_0s.png)
Python依赖管理及打包工具Poetry使用规范
2021-06-02 13:21:43
PyQt5根据控件Id获取控件对象的方法
2023-02-13 15:22:50
PHP如何从txt文件中读取数据详解
2023-11-15 02:37:32
![](https://img.aspxhome.com/file/2023/5/55725_0s.png)