Search code examples
pythonscikit-learngrid-search

ParameterGrid splits the string instead of combination


I'm trying to get the parameter grid for model selection. So, following the example in Sklearn documentation about ParameterGrid function we have this:

param_grid = {'a': [1, 2], 'b': [True, False]}
list(ParameterGrid(param_grid)) == (
                [{'a': 1, 'b': True}, {'a': 1, 'b': False},
                 {'a': 2, 'b': True}, {'a': 2, 'b': False}])

But what I want is pass only one value, without using list annotation ([]), like this:

param_grid = {'a': [1, 2], 'b': 'True', 'c': 'something'}

But then, list(ParameterGrid(param_grid)) just split all the strings instead of creation of two combinations. Result:

{'a': 1, 'b': 'T', 'c': 's'}
{'a': 1, 'b': 'T', 'c': 'o'}
{'a': 1, 'b': 'T', 'c': 'm'}

The question is, it's required to put all items in list format, or I'm missing something?


Solution

  • Yes, you need to use the [] notation, because the ParameterGrid expects the values to be an iterable. So when you set b as

    'b': 'True'
    

    It will iterate over the string 'True', hence you are getting different combinations with T, R, U and E.

    To fix this, use it like this

    param_grid = {'a': [1, 2], 'b': [True], 'c': ['something']}