我正在尝试结合cvxopt
(一个优化求解器)和PyMC(一个采样器)来解决凸型随机优化问题。
作为参考,使用安装两个软件包pip
非常简单:
pip install cvxopt
pip install pymc
两种软件包都可以独立完美完美地工作。这是如何解决LP问题的示例cvxopt
:
# Testing that cvxopt works
from cvxopt import matrix, solvers
# Example from http://cvxopt.org/userguide/coneprog.html#linear-programming
c = matrix([-4., -5.])
G = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]])
h = matrix([3., 3., 0., 0.])
sol = solvers.lp(c, G, h)
# The solution sol['x'] is correct: (1,1)
但是,当我尝试将其与PyMC配合使用时(例如,通过将分布放在系数之一上),PyMC会出现错误:
import pymc as pm
import cvxopt
c1 = pm.Normal('c1', mu=-4, tau=.5**-2)
@pm.deterministic
def my_lp_solver(c1=c1):
c = matrix([c1, -5.])
G = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]])
h = matrix([3., 3., 0., 0.])
sol = solvers.lp(c, G, h)
solution = np.array(sol['x'],dtype=float).flatten()
return solution
m = pm.MCMC(dict(c1=c1, x=x))
m.sample(20000, 10000, 10)
我收到以下PyMC错误:
<ipython-input-21-5ce2909be733> in x(c1)
14 @pm.deterministic
15 def x(c1=c1):
---> 16 c = matrix([c1, -5.])
17 G = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]])
18 h = matrix([3., 3., 0., 0.])
TypeError: invalid type in list
为什么?有什么办法可以使cvxopt
比赛变得更好PyMC
吗?
万一有人怀疑,PyMC允许您从您选择的任何功能中进行采样。在这种特殊情况下,我们从中采样的函数是将LP问题映射到解决方案的函数。我们正在从此函数中进行采样,因为我们的LP问题包含随机系数,因此不能仅仅采用现成的LP解算器。
更具体地说,在这种情况下,单个PyMC输出样本仅是LP问题的解决方案。随着LP问题的参数变化(根据您选择的分布),PyMC的输出样本将有所不同,希望是后验分布。
c1
生成with的类型pm.Normal
是numpy array
,您只需将其剥离并转换为float(c1)
,即可正常使用:
>>> @pm.deterministic
... def my_lp_solver(c1=c1):
... c = matrix([float(c1), -5.])
... G = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]])
... h = matrix([3., 3., 0., 0.])
... sol = solvers.lp(c, G, h)
... solution = np.array(sol['x'],dtype=float).flatten()
... return solution
...
pcost dcost gap pres dres k/t
0: -8.1223e+00 -1.8293e+01 4e+00 0e+00 7e-01 1e+00
1: -8.8301e+00 -9.4605e+00 2e-01 1e-16 4e-02 3e-02
2: -9.0229e+00 -9.0297e+00 2e-03 2e-16 5e-04 4e-04
3: -9.0248e+00 -9.0248e+00 2e-05 3e-16 5e-06 4e-06
4: -9.0248e+00 -9.0248e+00 2e-07 2e-16 5e-08 4e-08
Optimal solution found.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句