from sklearn import svm from sklearn.model_selection import GridSearchCV X_train, y_train = ... model = svm.SVC(kernel='linear') params = {'C': [0.1, 1, 10], 'penalty': ['l1', 'l2']} grid_search = GridSearchCV(model, params, scoring='accuracy', cv=5) grid_search.fit(X_train, y_train) print('Best parameters:', grid_search.best_params_) print('Best score:', grid_search.best_score_)
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV X_train, y_train = ... model = RandomForestClassifier() params = {'n_estimators': [50, 100, 200], 'max_depth': [5, 10, 20]} grid_search = GridSearchCV(model, params, scoring='f1_macro', cv=10) grid_search.fit(X_train, y_train) print('Best parameters:', grid_search.best_params_) print('Best score:', grid_search.best_score_)This code uses GridSearchCV to find the best combination of n_estimators and max_depth in a random forest model, using 10-fold cross-validation and the f1_macro metric to evaluate model performance. In both examples, the GridSearchCV function is imported from the sklearn.model_selection package, which is part of the Scikit-learn (sklearn) package library in Python.