首页 > 解决方案 > 如何使用 ParameterGrid 将多个列表作为输入,遍历所有组合并将结果输入到函数以测试所有选项

问题描述

我创建了一个函数,该函数具有多个输入,例如开始日期、期间、变量名称等。目前我必须手动将值输入到函数中以允许它开始运行,但我想尝试自动执行此操作。一些输入是恒定的,不需要更改,而另一些则需要更改结果。

我想使用迭代器更改的输入是:

train_period = [1, 4, 16, 39]

###The different test periods
test_start = ['2014-01-01 00:00', '2014-07-01 00:00']

###The different response variables
test_var = ['Temperature']

###Different step-ahead
step_ahead = [1, 4, 16, 96]

###Whether to consider smoothing or not
smoothing = [True, False]

###Define the grid of parameters to search
hyper_grid = {'train_period': train_period,
              'test_start': test_start, 
              'test_var': test_var,
              'step_ahead': step_ahead,
              'smoothing': smoothing}

from sklearn.model_selection import ParameterGrid

我确实尝试使用 parametergrid 使用 forloop 进行更改,但不幸的是它无法正常工作

grid = ParameterGrid(hyper_grid)
for params in grid:
    results dataframe format based on for loop index= Function(params['train_period'], params['test_start'], params['test_var'], params['step_ahead'], params['smoothing'])

结果应替换下面代码的函数端中的值,而不是固定值。

result1, result2, result3 = Function(fixedvalue1, fixedvalue2, train_period, test_start, test_period, test_var, step_ahead, smoothing = False)

标签: pythonfor-loopscikit-learniteration

解决方案


根据文档,您可以调用并且您的循环可以工作,但是您需要在循环的下一次迭代之前对您的结果进行索引或对它们做一些事情(例如保存性能指标)list()gridfor

grid = list(ParameterGrid(hyper_grid))
for params in grid:
    results = Function(params['train_period'], params['test_start'], params['test_var'], params['step_ahead'], params['smoothing'])

推荐阅读