Getting Started with scikit-learn

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

scikit-learn is an open source machine learning library for supervised and unsupervised learning. It also provides tools for data preprocessing, model selection, model evaluation and many other utilities. This page follows the structure of the official getting-started guide and expands each step: the two basic verbs (fit and predict), transformers, pipelines, model evaluation and automatic parameter search. It assumes you already know what a model, a training set and a test set are (see Machine Learning Fundamentals), and that scikit-learn is installed (see Installing scikit-learn).

The page targets scikit-learn 1.9 with NumPy 2.5 and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. All examples were run with Python 3.13.18, NumPy 2.5.4, pandas 3.1.0, SciPy 1.18.1 and scikit-learn 1.9.1, and the output shown is the real output. Each topic touched here has its own page later in this section, linked where it appears.

Fitting and predicting: estimator basics

Every learning algorithm in scikit-learn is an estimator: a Python object that is configured when you create it and learns from data when you call its fit method. Here a random forest classifier learns from two samples with three features each:

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier(random_state=0)
X = [[1, 2, 3],      # 2 samples, 3 features
     [11, 12, 13]]
y = [0, 1]           # the class of each sample

print(clf.fit(X, y))
print(clf.predict(X))                          # classes of the training data
print(clf.predict([[4, 5, 6], [14, 15, 16]]))  # classes of new data
print(clf.classes_, clf.n_features_in_)
RandomForestClassifier(random_state=0)
[0 1]
[0 1]
[0 1] 3

Three things to learn from this short example:

  1. fit(X, y) takes the samples matrix X of shape (n_samples, n_features) (rows are samples, columns are features) and the target y, which holds real numbers for regression or class labels for classification. For unsupervised learning y is omitted.

  2. fit returns the estimator itself, which is why print(clf.fit(X, y)) shows the estimator and why one-liners such as RandomForestClassifier().fit(X, y).predict(X_new) work.

  3. After fitting, the estimator exposes what it learned in attributes whose names end in an underscore, here classes_ and n_features_in_. You do not need to fit again to predict new data.

X and y are usually NumPy arrays or similar array-likes (lists, pandas data frames and series, SciPy sparse matrices for the estimators that support them). The exact meaning of each method and attribute is the subject of The Estimator API. Choosing which estimator to use is covered in Choosing the Right Estimator.

Transformers and pre-processors

Machine learning workflows are made of several parts: a pre-processing step that scales, encodes or imputes the data and a final predictor. In scikit-learn, pre-processors follow the same API as predictors. They have fit and, instead of predict, a transform method that returns a new samples matrix. Objects with transform are called transformers.

from sklearn.preprocessing import StandardScaler

X = [[0, 15],
     [1, -10]]

# learn the mean and standard deviation of each column, then apply them
print(StandardScaler().fit(X).transform(X))
[[-1.  1.]
 [ 1. -1.]]

fit computed one mean and one standard deviation per column, and transform subtracted and divided by them, so each column now has mean 0 and variance 1. The values computed by fit are kept in the transformer (mean_ and scale_), and a transformer fitted on the training data is later applied unchanged to test data. Shortcut: fit_transform(X) does both steps and is sometimes more efficient than calling them separately.

Different columns usually need different treatment: numeric columns are scaled, categorical columns are one-hot encoded. ColumnTransformer applies a different transformer to each group of columns; it is introduced in Scaling and Transforming Features.

Pipelines: chaining pre-processors and estimators

A Pipeline chains transformers and a final estimator into one object with the same API as an estimator: it is fitted with fit, and it predicts with predict. make_pipeline builds one and names the steps automatically from the class names. The example loads the classic Iris dataset, splits it into a training and a test set, fits the whole pipeline on the training part and scores it on the test part:

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

pipe = make_pipeline(StandardScaler(), LogisticRegression())

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

pipe.fit(X_train, y_train)          # scaler is fitted on the training data only
print(pipe)
print(accuracy_score(y_test, pipe.predict(X_test)))
print(pipe.score(X_test, y_test))   # same number: score is accuracy for classifiers
print(pipe.named_steps["standardscaler"].mean_)
Pipeline(steps=[('standardscaler', StandardScaler()),
                ('logisticregression', LogisticRegression())])
0.9736842105263158
0.9736842105263158
[5.88660714 3.05178571 3.79642857 1.22321429]

When pipe.fit runs, the scaler is fitted on the training data, the training data is transformed, and the logistic regression is fitted on the result. When pipe.predict runs on the test data, the already fitted scaler transforms it and the classifier predicts. named_steps gives access to each fitted step.

A pipeline is the main protection against data leakage, the situation in which information from the test data reaches the training process. If you scaled the whole dataset before splitting it, the mean and standard deviation would contain information about the test rows and the score would be optimistically biased. A pipeline fits every step on the training data only, also inside cross-validation. Leakage is explained in detail in Model Evaluation and Validation; the pipeline classes have their own page (Scaling and Transforming Features).

train_test_split shuffles by default. random_state=0 makes the split reproducible; without it, every run gives a different split and a different score. See Train/Test Split for stratification and the other options.

Model evaluation

A model that fits the training data well may predict new data badly, so it must be evaluated on data it has not seen. A single split gives one number that depends on the split. Cross-validation repeats the procedure on several splits. cross_validate runs 5-fold cross-validation by default:

from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_validate

X, y = make_regression(n_samples=1000, random_state=0)
result = cross_validate(LinearRegression(), X, y)   # defaults to 5-fold CV

print(sorted(result))
print(result["test_score"])   # R squared on each held-out fold
['fit_time', 'score_time', 'test_score']
[1. 1. 1. 1. 1.]

The returned dictionary holds the fitting time, the scoring time and the score of each fold. The score of a regressor is by default the coefficient of determination R squared; for a classifier it is accuracy. The dataset here is a noiseless synthetic linear problem, so the score is perfect. On real data the scores differ between folds, and the variation between folds is itself informative. The splitters (KFold, StratifiedKFold, GroupKFold, TimeSeriesSplit) and the scoring argument are described in Cross-Validation and Splitters and Metrics and Scoring.

Cross-validation of a whole pipeline works the same way, and it refits the scaler inside each fold:

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
print(cross_val_score(pipe, X, y, cv=5).round(3))
[0.967 1.    0.933 0.9   1.   ]

Automatic parameter searches

Estimators have parameters, often called hyperparameters, that control how they learn: the number of trees in a forest, the depth of each tree, the regularisation strength. Good values depend on the data. scikit-learn provides search objects that try combinations by cross-validation. The following example searches randomly over two parameters of a random forest:

from scipy.stats import randint
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV, train_test_split

# a synthetic dataset
X, y = make_regression(n_samples=20640, n_features=8, noise=0.1, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

# the parameter space to search
param_distributions = {"n_estimators": randint(1, 5), "max_depth": randint(5, 10)}

search = RandomizedSearchCV(
    estimator=RandomForestRegressor(random_state=0),
    n_iter=5,
    param_distributions=param_distributions,
    random_state=0,
)
search.fit(X_train, y_train)
print(search.best_params_)
# the search object now behaves like a forest fitted with the best parameters
print(round(search.score(X_test, y_test), 3))
{'max_depth': 9, 'n_estimators': 4}
0.844

After fit, the search object behaves like an estimator fitted with the best parameter combination (it refits on all of the training data by default), so it can be used directly with predict and score. The test set was never used to choose the parameters, which is why the final score is an honest estimate.

In practice you almost always search over a pipeline rather than a bare estimator, for the same leakage reason as above. Parameters of the steps are addressed with the step name, two underscores and the parameter name:

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))

grid = GridSearchCV(pipe, {"logisticregression__C": [0.1, 1, 10]}, cv=5).fit(X, y)
print(grid.best_params_, round(grid.best_score_, 3))
print(grid.predict(X[:3]))
{'logisticregression__C': 10} 0.973
[0 0 0]

The logisticregression__C syntax is explained in get_params, set_params and clone. The search classes are covered in Grid, Randomized and Halving Search. Note that the best score reported by a search is itself slightly optimistic, because the parameters were chosen to maximise it; keep a final test set, or use nested cross-validation, for the reported number.

What the first examples already show

Concept Where you saw it

Estimator with parameters set at creation

RandomForestClassifier(random_state=0)

fit(X, y), returns self

every example

Learned attributes ending in _

classes_, n_features_in_, mean_

Transformer with transform

StandardScaler

Pipeline behaves as an estimator

make_pipeline(StandardScaler(), LogisticRegression())

Reproducibility with random_state

train_test_split, forest, search

Scoring and cross-validation

score, cross_validate, cross_val_score

Hyperparameter search by cross-validation

RandomizedSearchCV, GridSearchCV

Differences from older tutorials

Many tutorials and books were written for scikit-learn 0.18 to 0.24 and contain code that no longer runs:

Older code Changed in Current code

from sklearn.cross_validation import train_test_split

0.18 (module removed in 0.20)

from sklearn.model_selection import train_test_split

from sklearn.grid_search import GridSearchCV, grid_scores_

0.18

sklearn.model_selection.GridSearchCV, cv_results_

from sklearn.preprocessing import Imputer

0.20

sklearn.impute.SimpleImputer

load_boston()

removed in 1.2

fetch_california_housing() or fetch_openml

plot_confusion_matrix(clf, X, y)

removed in 1.2

ConfusionMatrixDisplay.from_estimator(clf, X, y)

cv=3, forests with 10 trees, solver="liblinear"

defaults changed in 0.22

cv=5, n_estimators=100, lbfgs

positional hyperparameters such as KMeans(8, "k-means++")

keyword-only since 1.0

KMeans(n_clusters=8, init="k-means++")

The next page, The Estimator API, explains the conventions behind these examples.