如何更正 Python 中 OR 工具中的 objective 函数错误?

How can I correct objective function error in OR Tools in Python?

我正在使用 OR 工具解决 0-1 背包问题的变体。我设法解决了一种变体,但是,在这次尝试中,我在 objective 函数方面遇到了困难。这是我正在使用的代码。基本上,我想对 objective 函数中与某个项目关联的每个变量求和,然后如果选择了该项目,则 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()

我得到的错误特别是 objective 函数,但我不确定为什么(我有一个不同的版本使用单个 objective 系数)。错误是:

   return _pywraplp.Objective_SetCoefficient(self, var, coeff)

TypeError: in method 'Objective_SetCoefficient', argument 3 of type 'double'

您的数据很可能是 numpy.float()。将其转换为在 SetCoefficient 中浮动。