Stochastic Optimization in Python

2024/10/4 1:22:21

I am trying to combine cvxopt (an optimization solver) and PyMC (a sampler) to solve convex stochastic optimization problems.

For reference, installing both packages with pip is straightforward:

pip install cvxopt
pip install pymc 

Both packages work independently perfectly well. Here is an example of how to solve an LP problem with cvxopt:

# Testing that cvxopt works
from cvxopt import matrix, solvers# Example from http://cvxopt.org/userguide/coneprog.html#linear-programmingc = 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)

However, when I try using it with PyMC (e.g. by putting a distribution on one of the coefficients), PyMC gives an error:

import pymc as pm
import cvxoptc1 = 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 solutionm = pm.MCMC(dict(c1=c1, x=x))
m.sample(20000, 10000, 10)

I get the following PyMC error:

<ipython-input-21-5ce2909be733> in x(c1)14 @pm.deterministic15 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

Why? Is there any way to make cvxoptplay nicely with PyMC?

Background:

In case anyone wonders, PyMC allows you to sample from any function of your choice. In this particular case, the function from which we sample is one that maps an LP problem to a solution. We are sampling from this function because our LP problem contains stochastic coefficients, so one cannot just apply an LP solver off-the-shelf.

More specifically in this case, a single PyMC output sample is simply a solution to the LP problem. As parameters of the LP problem vary (according to distributions of your choice), the output samples from PyMC would be different, and the hope is to get a posterior distribution.

The solution above is inspired by this answer, the only difference is that I am hoping to use a true general solver (in this case cvxopt)

Answer

The type of c1 generated with pm.Normal is numpy array, you just need to strip it out and convert it to float(c1), then it works finely:

>>> @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/t0: -8.1223e+00 -1.8293e+01  4e+00  0e+00  7e-01  1e+001: -8.8301e+00 -9.4605e+00  2e-01  1e-16  4e-02  3e-022: -9.0229e+00 -9.0297e+00  2e-03  2e-16  5e-04  4e-043: -9.0248e+00 -9.0248e+00  2e-05  3e-16  5e-06  4e-064: -9.0248e+00 -9.0248e+00  2e-07  2e-16  5e-08  4e-08
Optimal solution found.
https://en.xdnf.cn/q/70661.html

Related Q&A

Pandas convert yearly to monthly

Im working on pulling financial data, in which some is formatted in yearly and other is monthly. My model will need all of it monthly, therefore I need that same yearly value repeated for each month. …

Firebase database data to R

I have a database in Google Firebase that has streaming sensor data. I have a Shiny app that needs to read this data and map the sensors and their values.I am trying to pull the data from Firebase into…

Django 1.8 Migrations - NoneType object has no attribute _meta

Attempting to migrate a project from Django 1.7 to 1.8. After wrestling with code errors, Im able to get migrations to run. However, when I try to migrate, Im given the error "NoneType object has …

Manage dependencies of git submodules with poetry

We have a repository app-lib that is used as sub-module in 4 other repos and in each I have to add all dependencies for the sub-module. So if I add/remove a dependency in app-lib I have to adjust all o…

Create Boxplot Grouped By Column

I have a Pandas DataFrame, df, that has a price column and a year column. I want to create a boxplot after grouping the rows based on their year. Heres an example: import pandas as pd temp = pd.DataF…

How can I configure gunicorn to use a consistent error log format?

I am using Gunicorn in front of a Python Flask app. I am able to configure the access log format using the --access-log-format command line parameter when I run gunicorn. But I cant figure out how to c…

Implementing seq2seq with beam search

Im now implementing seq2seq model based on the example code that tensorflow provides. And I want to get a top-5 decoder outputs to do a reinforcement learning.However, they implemented translation mode…

Pandas Random Weighted Choice

I would like to randomly select a value in consideration of weightings using Pandas.df:0 1 2 3 4 5 0 40 5 20 10 35 25 1 24 3 12 6 21 15 2 72 9 36 18 63 45 3 8 1 4 2 7 5 4 16 2 8 4…

Matplotlib TypeError: NoneType object is not callable

Ive run this code many times but now its failing. Matplotlib wont work for any example, even the most trivial. This is the error Im getting, but Im not sure what to make of it. I know this is vague and…

Resize image faster in OpenCV Python

I have a lot of image files in a folder (5M+). These images are of different sizes. I want to resize these images to 128x128. I used the following function in a loop to resize in Python using OpenCVdef…