有没有办法对谷歌或工具 pywrapknapsack_solver 施加内存限制?

问题描述

我创建了 5,000 个背包数据集实例,每个数据集包括 100 个重量、100 个值、总重量和容量百分比。权重和值具有均值 100 和标准 5 的正态分布。输入文件是格式为 [张量(权重)、张量(值)、张量(总重量)、容量百分比] 的泡菜。 The pickle input file

我创建了一个 Python 程序,它接收输入文件,使用 google 或工具 pywrapknapsack_solver 解决问题,并将解决方输出为 one-hot 向量和解决时间。

import torch 
from ortools.algorithms import pywrapknapsack_solver
import time
import pickle
import argparse

def translate_soln(packed_items,num_items):
    out = [0]*num_items
    for i in packed_items:
        out[int(i)] = 1
    return out


def knapsack_solution_generator(input_path,output_path):
    input_data = pickle.load( open(input_path,'rb'))

    weights = input_data[0].tolist()
    values = input_data[1].tolist()

    total_weight = input_data[2].item()
    capacity_percentage = input_data[3]
    capacity = [total_weight * (capacity_percentage / 100)]

    num_items = len(weights)

    solver = pywrapknapsack_solver.KnapsackSolver(
            pywrapknapsack_solver.KnapsackSolver.
            KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,'KnapsackExample')
    solver.set_time_limit(7200)
    
    start_time = time.perf_counter()
    solver.Init(values,[weights,capacity)
    
    computed_value = solver.solve()
    end_time = time.perf_counter()

    solution_time = round(end_time - start_time,5)

    packed_items = []
    for j in range(num_items):
        if solver.BestSolutionContains(j):
            packed_items.append(j)

    solution = translate_soln(packed_items,num_items)
    pickle.dump((solution,solution_time),open(output_path,'wb'))
    

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('--input',type=str,help="Input file path")
    parser.add_argument('--output',help="Output file path")
    
    args = parser.parse_args()
    input_path = args.input
    output_path = args.output

    knapsack_solution_generator(input_path,output_path)

我一直在使用 Linux 虚拟机来独立解决所有这些问题。但是,当机器尝试解决容量百分比范围为 10-90% 的问题时,某些问题实例无法解决。查看输出日志时,有一个“Killed error”。为了更深入地挖掘,我让机器再次尝试解决问题实例,因为我使用 linux top 命令进行监控,发现无法解决的问题在大约 20 分钟后以 80% 的内存被杀死。但是,某些问题将在 2 小时内解决。是什么导致求解器占用过多内存?有没有办法实现内存约束?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)