【问题标题】:AttributeError: module 'cplex' has no attribute 'Cplex'AttributeError:模块“cplex”没有属性“Cplex”
【发布时间】:2019-10-08 07:05:41
【问题描述】:

我正在尝试在 Python 中使用 CPLEX 优化线性规划问题。 我已经安装了 IBM ILOG CPLEX Studio,以及 Python 中的 docplex。

当我运行程序时出现以下错误:

AttributeError: module 'cplex' has no attribute 'Cplex'

有用的代码:

import docplex.mp.model as cpx

import random

import pandas as pd

n = 10
m = 5
set_I = range(1, n+1)
set_J = range(1, m+1)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}


opt_model = cpx.Model(name="MIP Model")

# if x is Binary
x_vars  = {(i,j): opt_model.binary_var(name="x_{0}_{1}".format(i,j)) for i in set_I for j in set_J}


# <= constraints
constraints = {j : opt_model.add_constraint(ct=opt_model.sum(a[i,j] * x_vars[i,j] for i in set_I) <= b[j], ctname="constraint_{0}".format(j)) for j in set_J}

objective = opt_model.sum(x_vars[i,j] * c[i,j] for i in set_I  for j in set_J)

opt_model.minimize(objective)

opt_model.solve()


opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns = ["variable_object"])

opt_df.index = pd.MultiIndex.from_tuples(opt_df.index, names=["column_i", "column_j"])
opt_df.reset_index(inplace=True)

opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.solution_value)

print(opt_df)

我从https://medium.com/@m.moarefdoost/optimization-modeling-in-python-pulp-gurobi-and-cplex-7f25acb03d7d提取了这段代码

我是 CPLEX 和 Python 的初学者,所以我只是尝试运行此代码来验证我是否已正确安装所有内容。

有人遇到过同样的问题吗?

【问题讨论】:

  • 您能出示您的完整代码吗?这应该工作:import cplex 然后cplex.Cplex()。这会产生同样的错误吗?
  • @DanielJunglas 感谢您的快速回复。我编辑了我的问题并添加了代码,希望它可以帮助您理解我的麻烦。
  • 能否请您也添加错误消息的完整回溯?我没有看到你在任何地方使用cplex 包。还要确保您的 PYTHONPATH 环境变量设置正确并指向包含 CPLEX Python 库的目录。
  • 顺便说一句:您的代码在我的机器上运行没有任何问题。
  • @DanielJunglas,我的 setup.py 没有正确安装,但现在我纠正了,我的代码运行正常。非常感谢您花时间帮助我!

标签: python attributeerror cplex


【解决方案1】:

我发现我的代码有错误。 实际上,在运行我的代码之前,我没有正确安装 setup.py。

完成后,一切正常!

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。我在设置 CPLEX 的 Python API 时犯了几个错误。

    1. 我没有使用位于 yourCplexhome/python/VERSION/PLATFORM 的脚本 setup.py,而是使用位于 CPLEX_Studio1210/python 的脚本 setup.py。
    2. 我没有将Python路径环境变量PYTHONPATH设置为yourCplexhome/python/VERSION/PLATFORM的值

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 2019-02-18
      • 1970-01-01
      • 2020-01-01
      • 2019-07-20
      相关资源
      最近更新 更多