安装cvxpy时解决ImportError: No module named multiprocessing

参加ICASSP2016时了解到Python下有一个优化工具包cvxpy,代码形式非常简洁,于是想尝试一下。

1.环境

本机环境windows 10 x64 + python2.7。

2.安装方法

运行如下命令:

pip install cvxpy

执行样例代码

from cvxpy import *
import numpy

# Problem data.
m = 30
n = 20

numpy.random.seed(1)
A = numpy.random.randn(m, n)
b = numpy.random.randn(m)

# Construct the problem.
x = Variable(n)
objective = Minimize(sum_squares(A*x - b))
constraints = [0 <= x, x <= 1]
prob = Problem(objective, constraints)

# The optimal objective is returned by prob.solve().
result = prob.solve()
# The optimal value for x is stored in x.value.
print(x.value)
# The optimal Lagrange multiplier for a constraint
# is stored in constraint.dual_value.
print(constraints[0].dual_value)

运行时出现ImportError:找不到cvxpy包。在命令行只运行python命令,执行

from cvxpy import *

后可以看到问题的根源在于实际上在“PYTHON_ROOT\Lib\site-packages\multiprocess\__init__.py”文件的第84行(其中PYTHON_ROOT为你的python根目录)。

通过在Github上查看multiprocess项目的最新源码,将__init__.py文件中的

# This is down here because _multiprocessing uses BufferTooShort
    import _multiprocess as _multiprocessing

替换为

# This is down here because _multiprocessing uses BufferTooShort
try:
    import _multiprocess as _multiprocessing
except ImportError:
    import _multiprocessing

(https://github.com/uqfoundation/multiprocess/blob/master/py2.7/multiprocess/__init__.py)

卸载cvxpy后再安装一次:

pip uninstall cvxpy
pip install cvxpy

此时样例代码可以正常执行了,可以再执行

pip install nose
nosetests cvxpy

测试cvxpy的所有功能是否正常。

你可能感兴趣的:(编译环境)