Programming Language: Python

Namespace/Package Name: sklearn.grid_search

Class/Type: GridSearchCV

Examples at hotexamples.com: 60

The sklearn.grid_search.GridSearchCV is a function provided in the Scikit-learn package library for hyperparameter tuning in machine learning models. It allows for an exhaustive search of specified hyperparameters to optimize model performance on a given metric.

Below are some examples of using GridSearchCV in Python:

1. Grid search for a linear support vector machine (SVM) model with different values of C and penalty:

This code uses GridSearchCV to find the best combination of C and penalty in a linear SVM model, using 5-fold cross-validation to evaluate model performance.

2. Grid search for a random forest model with different values of n_estimators and max_depth:

Below are some examples of using GridSearchCV in Python:

1. Grid search for a linear support vector machine (SVM) model with different values of C and penalty:

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_)

This code uses GridSearchCV to find the best combination of C and penalty in a linear SVM model, using 5-fold cross-validation to evaluate model performance.

2. Grid search for a random forest model with different values of n_estimators and max_depth:

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.

Frequently Used Methods

Frequently Used Methods

Related

Related in langs