Search code examples
pythonmachine-learningscikit-learngrid-searchgridsearchcv

GridSearchCV for multiple models


I'm trying to create a GridSearch CV function that will take more than one model. However, I've the following error: TypeError: not all arguments converted during string formatting

def grid(model, X_train,y_train):
    grid_search = GridSearchCV(model, parameters, cv=5)
    grid_search.fit(X_train, y_train)
    prediction = grid_search.predict(X_test)
    best_classifier = grid_search.best_estimator_

    return grid_search

clf = [('DecisionTree',DT()),('RandomForest',RF())

n_folds = 15

for model in clf:
    
    print('\nWorking on ', model[0])
    
    grid_search = grid(model,X_train,y_train)

Solution

  • You have stored your models in a list of tuples (note that in your example the closing bracket is actually missing):

    clf = [('DecisionTree', DT()), ('RandomForest', RF())]
    

    Since you iterate through all tuples and your actual models are stored at index 1 of each of them, you have to pass model[1] to your function:

    for model in clf:
        print('\nWorking on ', model[0])
        grid_search = grid(model[1], X_train, y_train) # <-- change in this line