Hyperparameter Tuning

Python · Machine Learning (Scikit-Learn)

Theory

Hyperparameters are settings you choose before training, such as max_depth of a tree, n_neighbors in KNN or C in logistic regression; the model does not learn them from data. GridSearchCV tries every combination in a param_grid, scores each one with cross-validation on the training set and keeps the best. After fit, best_params_ holds the winning settings, best_score_ its mean cross-validated score, and best_estimator_ a model refitted on the whole training set with those settings.

cv_results_ contains the full table of mean and std scores per combination, which is easy to view with pd.DataFrame. The number of fits grows fast: 3 values x 4 values x 5 folds is 60 fits, so RandomizedSearchCV, which samples n_iter combinations, is better for large grids. To tune a pipeline, name parameters as step__param, for example {'model__C': [0.1, 1, 10]}. Report the final score on the untouched test set.

Why we use it

Default settings are rarely the best for your data. Systematic, cross-validated search finds better settings without peeking at the test set, so the improvement you report is real rather than tuned to one lucky split.

When to use it

Tune after you have a working pipeline and a baseline score. Use GridSearchCV for a few parameters with a handful of values each, RandomizedSearchCV for many parameters or wide ranges. Keep the test set out of the search.

How it works

  1. Pipeline and a baseline score
  2. Define param_grid with a few values per setting
  3. For each combination run k-fold cross-validation
  4. Rank combinations by mean CV score
  5. Is the best value at the edge of the grid? Yes: Extend the grid and search again. No: Accept best_params_.
  6. Score best_estimator_ once on the test set

Syntax

from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(estimator, param_grid={'max_depth': [2, 3, 5]}, cv=5, scoring='accuracy')
grid.fit(X_train, y_train)
grid.best_params_, grid.best_score_
grid.best_estimator_.score(X_test, y_test)

Example

grid = GridSearchCV(pipe, {'model__C': [0.1, 1, 10]}, cv=5)
grid.fit(X_train, y_train)
print(grid.best_params_, grid.best_score_)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic