what is scikit learn

What Is Scikit-Learn? Uses & First Python Example

Hey friends! Scikit-learn is a free, open-source Python library for machine learning. It helps you prepare data, train models, and evaluate predictions for tasks such as classification, regression, and clustering. You install it as scikit-learn and import it as sklearn.

Think of it as a toolbox: the algorithms are ready to use, but you still decide what problem to solve, which examples the model can learn from, and how to judge its mistakes. Let’s make those decisions concrete with a small Python project.

Scikit-learn Python machine learning library logo

What is scikit-learn used for?

Your goalTaskExample tools
Predict a category, such as a wine varietyClassificationLogisticRegression, KNeighborsClassifier, RandomForestClassifier
Predict a number, such as delivery timeRegressionLinearRegression, RandomForestRegressor
Find groups without known labelsClusteringKMeans, DBSCAN
Reduce the number of input dimensionsDimensionality reductionPCA
Prepare inputs and compare modelsPreprocessing and evaluationStandardScaler, Pipeline, cross-validation

You do not need to implement every algorithm yourself. Start with a simple baseline and a model that fits your task. Our machine learning algorithms guide explains the main choices.

Scikit-learn vs pandas and deep learning libraries

Pandas helps you load, inspect, join, and organize tabular data. Scikit-learn adds machine learning models and evaluation tools. They often belong in the same project; learn the data-handling basics in our pandas introduction.

Scikit-learn includes basic neural network estimators, but it is not a general framework for building large deep learning architectures. For projects centered on custom neural networks, tools such as PyTorch or TensorFlow serve a different purpose. For a first project with rows and columns of measurements, scikit-learn is a useful starting point.

Want a clear learning order? Grab the Free Machine Learning Roadmap and use it to plan your Python, data preparation, and modelling practice.

How to install scikit-learn

In your terminal, use the Python environment where you will run your project:

python -m pip install -U scikit-learn

Inside a Jupyter or Colab notebook, use %pip install -U scikit-learn if installation is needed. If the notebook requests a runtime restart after upgrading, restart before running the example. Check the import with:

import sklearn
print(sklearn.__version__)

The package name and import name are different: install scikit-learn, import sklearn. For environment-specific instructions, see the official installation guide.

Your first scikit-learn example: classify wine

Our mission is to predict one of three wine classes from chemical measurements. The dataset is bundled with scikit-learn, so you do not need an account or a CSV download. Each row is a sample; the columns are measurements. X holds those inputs, and y holds the class labels.

Before running: predict whether always guessing the most common class will be a useful benchmark. Then read the code in four steps: split the examples, fit a baseline, train a pipeline, and evaluate on the reserved test set.

from sklearn.datasets import load_wine
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)

baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)

model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
model.fit(X_train, y_train)
predictions = model.predict(X_test)

print("Training rows:", len(X_train))
print("Test rows:", len(X_test))
print(f"Baseline accuracy: {accuracy_score(y_test, baseline.predict(X_test)):.3f}")
print(f"Model accuracy: {accuracy_score(y_test, predictions):.3f}")
print("Confusion matrix:")
print(confusion_matrix(y_test, predictions))

With scikit-learn 1.8.0, this example produced 133 training rows and 45 test rows, baseline accuracy 0.400, and model accuracy 0.933. That means the model classified 42 of 45 test examples correctly. This is a small teaching dataset and one split, not a guarantee of performance on new real-world data.

The baseline makes the result meaningful: 93.3% accuracy beats the 40% obtained by always predicting the most common training class. Accuracy alone can hide costly errors or class imbalance; our model evaluation guide helps you choose an appropriate metric.

Understand fit, transform, and predict

An estimator is an object with a fit method that learns from data. Transformers are estimators too; they are not a separate, opposing category. StandardScaler.fit learns training-set scaling statistics, and transform applies them. A predictor such as KNeighborsClassifier uses predict to return class labels.

In our example, make_pipeline joins scaling and classification. Calling model.fit(X_train, y_train) learns the scaler from training rows and fits the classifier on the transformed training inputs. Calling model.predict(X_test) applies those same learned scaling rules before predicting.

Scaling matters here because nearest neighbours use distances: a feature measured on a large numerical scale can otherwise dominate. The feature scaling guide explains that choice. For mixed numeric and categorical columns, continue with Pipeline and ColumnTransformer.

Your challenge: unlock the three-number combination

Pause before the answer section. Read the code and confusion matrix, then find these three numbers in order: training rows, correct test predictions, mistakes involving true class 2. Scikit-learn labels these classes 0, 1, and 2. In this confusion matrix, rows are true classes and columns are predicted classes.

Bonus question: a friend scales all 178 rows before splitting them. Why is that a problem, even though scaling does not use the class labels? Write your explanation before checking below.

Three mistakes to avoid

Learning preprocessing from the test set. Split first, then fit learned transformations on training data. A pipeline helps keep these steps together; it does not fix a poor split or features that reveal the answer.

Tuning until the test score looks good. If you compare neighbour counts or other settings, use cross-validation within the training data. Keep the test set for a final check. Repeatedly selecting settings against it makes it part of your selection process.

Treating a cheat sheet as proof. Algorithm maps suggest candidates, but your validation results and problem constraints decide what works. This overview is a starting point:

what is scikit learn cheat sheet

For the maintained interactive version, visit scikit-learn’s estimator selection guide.

Challenge answers and explanations

The combination is 133–42–1. There are 133 training rows. The diagonal of the confusion matrix gives correct predictions: 15 + 16 + 11 = 42. The final row represents true class 2: one example was predicted as class 1, while eleven were correct.

The scaling trap: fitting the scaler before splitting lets held-out examples influence the preprocessing statistics. Even without labels, this leaks information from the test set into training. Fit the scaler using training rows only, and reuse it on test rows. The pipeline in the example does this for you.

What should you learn next?

Keep the momentum, friends! Work through our first machine learning project in Python, then practise choosing a metric and comparing a baseline. Once that workflow makes sense, move on to cross-validation and hyperparameter tuning.

Choose your next step: the Free Roadmap helps you organize what to learn. For a guided companion, explore the ML Starter Kit or read its free sample.

Reference guides: scikit-learn getting started and common pitfalls and recommended practices.

what is scikit-learn

Subscribe to our awesome newsletter to get the best content on your journey to learn Machine Learning, including some exclusive free goodies!

HOW IS MACHINE LEARNING