OnY
OnY

Reputation: 897

How to define the grid (for using grid search) from scratch in Python?

I write a function that accepts a dictionary of parameter names (could be of any size>0) and numeric values, and returns a list of dictionaries with all the possible combinations.

For example:

myFunc({'ParA':[1,2,3], 'ParB': [0.1,0.2,0.3,0.4]})

Will return

[{'ParA':1, 'ParB':0.1},{'ParA':1, 'ParB':0.2}...{'ParA':2, 'ParB':0.1}....{'ParA':3, 'ParB':0.4}]

Normally I'd use nested loops, but I do not know the number of parameters in advance.

Another challenge is that the number of possible values in each parameter changes, so the lengths are not sorted in the dictionary.

Is there a smart way of doing that?

Note: it has to be from scratch, so no grid-search functions from SciPy

Upvotes: 0

Views: 1233

Answers (1)

OnY
OnY

Reputation: 897

Here is the solution based on Julien's answer (itertools.product):

def makeGrid(pars_dict):  
    keys=pars_dict.keys()
    combinations=itertools.product(*pars_dict.values())
    ds=[dict(zip(keys,cc)) for cc in combinations]
    return ds

Upvotes: 1

Related Questions