问题描述
我正在尝试使用 cvxpy 来解决整数线性规划 (ILP)。由于我需要运行数千次相同的 ILP(具有不同的参数矩阵)来解决我的问题,因此我需要改进运行时间。
教程中提供的一种方法是使用 cp.Parameter
作为程序中的参数,而无需重复构造相同的 cp.Problem
(请参阅 cvxpy tutorial)。基于此,人们可以使用 multiprocessing
库来利用多个处理器的能力。
但是,当我尝试比较两个版本的简单回归问题(一个使用 cp.Parameter
和一个不使用)时,我看不到教程中声称的加速:
参数的目的是在不重构整个问题的情况下改变问题中常量的值。在许多情况下,多次解决参数化程序比重复解决新问题要快得多。
两个版本代码的运行时间如下
successfully solved problem 10 / 10 times...
func: 'solveWithParam' args: [(500,400),{}] took: 21.6852 sec
successfully solved problem 10 / 10 times...
func: 'solveWithoutParam' args: [(500,{}] took: 16.2620 sec
我用来获得这个结果的代码如下
import numpy as np
import cvxpy as cp
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrap(*args,**kwargs):
ts = time()
result = f(*args,**kwargs)
te = time()
print("func: %r args: [%r,%r] took: %2.4f sec" % \
(f.__name__,args,kwargs,te-ts))
return result
return wrap
@timing
def solveWithParam(m,n,K=10):
np.random.seed(0)
x = cp.Variable(n)
A = cp.Parameter((m,n))
b = cp.Parameter(m)
objective = cp.Minimize(cp.sum_squares(A @ x - b))
constraints = [0 <= x,x <= 1]
problem = cp.Problem(objective,constraints)
cnt = 0
for _ in range(K):
A.value = np.random.rand(m,n)
b.value = np.random.rand(m)
problem.solve()
if problem.status == cp.OPTIMAL: cnt += 1
print("successfully solved problem %d / %d times..." % (cnt,K))
@timing
def solveWithoutParam(m,K=10):
np.random.seed(0)
cnt = 0
for _ in range(K):
x = cp.Variable(n)
A = np.random.rand(m,n)
b = np.random.rand(m)
objective = cp.Minimize(cp.sum_squares(A @ x - b))
constraints = [0 <= x,x <= 1]
problem = cp.Problem(objective,constraints)
problem.solve()
if problem.status == cp.OPTIMAL: cnt += 1
print("successfully solved problem %d / %d times..." % (cnt,K))
m = 500
n = 400
solveWithParam(m,n)
solveWithoutParam(m,n)
我不确定我在这里遗漏了什么,是不是因为这种情况下的问题太简单了?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)