如何纠正 Python 中 OR 工具中的目标函数错误?
Posted
技术标签:
【中文标题】如何纠正 Python 中 OR 工具中的目标函数错误?【英文标题】:How can I correct objective function error in OR Tools in Python? 【发布时间】:2022-01-09 00:04:22 【问题描述】:我正在使用 OR 工具解决 0-1 背包问题的变体。我已经设法解决了一种类型的变化,但是,在这次尝试中,我在目标函数方面遇到了困难。这是我正在使用的代码。基本上,我想将与目标函数中的项目关联的每个变量求和,然后如果选择了项目,则 x[i,j] 二进制变量将设置为 1:
import math
import pandas as pd
import ortools
from ortools.linear_solver import pywraplp
solver = solver = pywraplp.Solver.CreateSolver('SCIP')
#All of the variables in the dataframe are integer variables
df = pd.read_csv('data.csv')
#Create a data dictionary to store all of the data items in
data =
data['ID'] = df.ID
data['time'] = df.Time
data['days'] = df.Days
data['canc'] = df.Canc
data['hdu'] = df.HDU
data['priority'] = df['Priority']
data['items'] = list(range(len(df.ID)))
data['num_items'] = len(df.ID)
num_knapsacks = 2
data['capacities'] = [480,240]
data['knapsacks'] = list(range(num_knapsacks))
x =
for i in data['items']:
for j in data['knapsacks']:
x[(i,j)] = solver.IntVar(0,1,'x_%i_%i' % (i, j))
#Constraint to limit item to a single knapsack
for i in data['items']:
solver.Add(sum(x[i,j] for j in data['knapsacks'])<=1)
#Knapsack Capacity Constraint
for j in data['knapsacks']:
solver.Add(sum(x[(i,j)]*data['time'][i]
for i in data['items']) <= data['capacities'][j])
# HDU Constraint
for j in data['knapsacks']:
solver.Add(sum(x[(i,j)]*data['hdu'][i]
for i in data['items']) <= 1)
#objective function
objective = solver.Objective()
for i in data['items']:
for j in data['knapsacks']:
objective.SetCoefficient(x[(i,j)], data['days'][i]+data['time'][i]+data['priority'][i]+data['canc'][i])
objective.SetMaximization()
我得到的错误专门针对目标函数,但我不知道为什么(我得到了一个使用单个目标系数的不同版本)。错误是:
return _pywraplp.Objective_SetCoefficient(self, var, coeff)
TypeError: in method 'Objective_SetCoefficient', argument 3 of type 'double'
【问题讨论】:
【参考方案1】:您的数据很可能是 numpy.float()。将其转换为在 SetCoefficient 中浮动。
【讨论】:
太棒了!谢谢,成功了!以上是关于如何纠正 Python 中 OR 工具中的目标函数错误?的主要内容,如果未能解决你的问题,请参考以下文章