我正在尝试合并 cvxopt
(优化求解器)和 PyMC (采样器)解决凸随机优化问题。
作为引用,使用 pip
安装这两个包非常简单:
pip install cvxopt
pip install pymc
这两个包独立运行得很好。以下是如何使用 cvxopt
解决 LP 问题的示例:
# 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输出的样本也会不同,希望得到后验分布。
上述解决方案的灵感来自 this answer ,唯一的区别是我希望使用真正的通用求解器(在本例中为 cvxopt
)
最佳答案
用pm.Normal
生成的c1
类型是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.
关于python - Python 中的随机优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25076711/