Machine Learning with Scikit-Learn, Step by Step
Built from a real working notebook, refined into a teaching document.
📖 How to Use This Document
This is a reference you can come back to, not something you need to memorize in one sitting.
- New to ML? Start from the beginning and follow the examples in order.
- Already comfortable? Jump directly to the section you need, such as evaluation metrics, hyperparameter tuning, pipelines, or saving models.
- Following the code? Every example uses real, runnable Scikit-Learn code.
- Learning the concepts? Each important idea is explained before the code that uses it.
The goal is simple:
You should understand why you're writing the code, not just know what to type.
📦 Datasets Used in This Tutorial
We'll use four datasets throughout the tutorial.
| Dataset | Download link |
|---|---|
| Heart Disease (CSV) | 🔗 Link |
| California Housing | ✅ Built into Scikit-Learn (fetch_california_housing()) — no download needed |
| Car Sales (CSV) | 🔗 Link |
| Car Sales Extended (with missing data) (CSV) | 🔗 Link |
💡 Tip: If you're using Google Colab, upload the CSV files to your Colab session or mount Google Drive. Then make sure the file path in your code points to the correct location.
📚 Table of Contents
- What is Machine Learning?
- The Scikit-Learn Workflow (the big picture)
- Setup
- Getting Your Data Ready
- Choosing the Right Estimator
- Fitting a Model and Making Predictions
- Evaluating a Model
- Improving a Model
- Saving and Loading a Trained Model
- Putting It All Together (Pipelines)
- Common Errors & How to Fix Them
- Quick-Reference Cheat Sheet
1. What is Machine Learning?
Machine Learning (ML) is a way of building computer programs that learn patterns from examples. In traditional programming, you write the rules. In machine learning, you give the computer examples and let the algorithm learn the rules.
Traditional programming vs. machine learning
| Traditional Programming | Machine Learning | |
|---|---|---|
| You provide | Explicit rules | Examples |
| The computer | Follows your rules | Finds patterns in the examples |
| Output | Result based on your rules | A learned model that can make predictions |
| Good for | Problems with clear rules | Problems where rules are difficult to write manually |
🧠 A simple example
Imagine you want a computer to recognize dogs in pictures. With traditional programming, you might try to write rules such as:
"If the picture has four legs, fur, two ears, and a tail, call it a dog."
But this quickly becomes difficult. Some dogs are sitting, some are lying down, some are partially hidden, and other animals can have similar characteristics. With machine learning, you can instead give the computer many examples:
Picture → Dog Picture → Dog Picture → Not Dog Picture → Dog Picture → Not Dog ... The algorithm looks at these examples and learns patterns that help it distinguish dogs from other things. That's the basic idea behind machine learning.
The same idea works for many problems:
- Spam detection → learn from emails labelled spam/not spam.
- House price prediction → learn from houses and their known prices.
- Medical prediction → learn from patient information and known outcomes.
In every case, we have:
Inputs → Model → Prediction The inputs are usually called features, and the answer we're trying to predict is called the target or label.
Where Scikit-Learn fits
Scikit-Learn is a Python library that provides many tools for machine learning. It is especially useful for structured data — data organized into rows and columns.
For example:
Age Salary Experience Purchased 25 40000 2 0 32 60000 5 1 41 90000 10 1 This looks like a spreadsheet, which makes it a good fit for Scikit-Learn.
| Data type | Examples | Common tools |
|---|---|---|
| Structured | CSVs, SQL tables, spreadsheets | Scikit-Learn |
| Unstructured | Images, audio, video, raw text | Deep learning frameworks such as PyTorch/TensorFlow |
🎯 Rule of thumb: If your data naturally looks like rows and columns, Scikit-Learn is a very good place to start.
2. The Scikit-Learn Workflow (the big picture)
Most basic Scikit-Learn projects follow the same general process. Learn this flow because you'll see it again and again:
1. Get data ready ↓ 2. Pick a model ↓ 3. Fit the model to data ↓ 4. Make predictions ↓ 5. Evaluate the model ↓ Good enough? ── no ──▶ 6. Improve via tuning ──┐ │ yes │ │ │ ▼ │ 7. Save and reload the model ◀────────────────────┘ Let's translate that into normal language.
1. Get your data ready
Load your data and prepare it so the model can use it. This might involve:
- separating features and targets
- handling missing values
- converting text categories into numbers
- scaling features when necessary
2. Pick a model
Choose an algorithm that matches your problem. For example:
- Predicting Yes/No → classification
- Predicting a price → regression
3. Fit the model
Give the model training examples.
model.fit(X_train, y_train) This is where the model learns patterns from your data.
4. Make predictions
Give the trained model data it hasn't seen before.
model.predict(X_test) 5. Evaluate
Check how good those predictions are. For example:
Classification metrics
- Accuracy
- Precision
- Recall
- F1
Regression metrics
- R²
- MAE
- MSE
The metric depends on the problem.
6. Improve
If the model isn't good enough, experiment. You might:
- improve the data
- try another model
- change model settings
- tune hyperparameters
- add or remove useful features
7. Save
Once you have a model you're happy with, save it to disk.
Then you can load it later without training it again.
🚀 A first end-to-end example
Before learning each individual piece, let's look at the whole process. Don't worry if some lines don't make sense yet. We'll explain each part later.
# 1. Get the data ready import pandas as pd heart_disease = pd.read_csv("sklearn-heart-disease.csv") X = heart_disease.drop("target", axis=1) # features y = heart_disease["target"] # labels # 2. Choose the right model/estimator from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier() # 3. Fit the model to the training data from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1 ) clf.fit(X_train, y_train) # 4. Make a prediction y_preds = clf.predict(X_test) # 5. Evaluate the model clf.score(X_train, y_train) # accuracy on data it has already seen clf.score(X_test, y_test) # accuracy on data it has NOT seen — this is what matters from sklearn.metrics import classification_report, confusion_matrix, accuracy_score print(classification_report(y_test, y_preds)) confusion_matrix(y_test, y_preds) accuracy_score(y_test, y_preds) # 6. Improve the model (a simple manual sweep) for i in range(10, 100, 10): clf = RandomForestClassifier(n_estimators=i).fit(X_train, y_train) print(f"n_estimators={i} -> test accuracy: {clf.score(X_test, y_test) * 100:.2f}%") # 7. Save the model and load it back import pickle pickle.dump(clf, open("random_forest_model_1.pkl", "wb")) loaded_model = pickle.load(open("random_forest_model_1.pkl", "rb")) loaded_model.score(X_test, y_test) This is the basic machine learning loop:
Data → Split → Train → Predict → Evaluate → Improve → Save That's the entire universe of a basic ML project. Everything else in this handbook goes deeper into each of these seven steps.
3. Setup
Let's get the environment ready. Only a handful of lines.
📂 Mount Google Drive (if using Colab)
If you're using Google Colab and your datasets are stored in Google Drive, you can connect your Drive like this:
from google.colab import drive drive.mount('/content/drive') After running this, Colab will ask you for permission. Once connected, your Drive becomes accessible through /content/drive/. If you're running the notebook locally, you don't need this.
💡 If running locally, skip this and use direct file paths.
📊 Standard Imports
# Import NumPy for numerical operations and working with arrays import numpy as np # Import Pandas for working with data and DataFrames import pandas as pd # Import Matplotlib for creating visualizations and plots import matplotlib.pyplot as plt # Display Matplotlib plots directly inside the Jupyter Notebook %matplotlib inline 📝 A note on GPUs: Scikit-Learn runs on the CPU. Unlike deep learning, you don't need a GPU — checking
!nvidia-smiin Colab is harmless but irrelevant here.
4. Getting Your Data Ready
This is where a lot of the real work in machine learning happens. Training a model is often just a few lines of code. The harder part is preparing the data so the model can actually learn from it.
There are three important things we usually need to do:
- Split the data into features and labels — usually called
Xandy. - Handle missing values — fill them with a suitable value (imputation) or remove the rows/columns containing them.
- Convert non-numeric data into numbers — this is called feature encoding.
We'll go through each of these steps one by one. Before we can do any of that, we need data loaded into the notebook.
Load the Heart Disease dataset:
heart_disease = pd.read_csv("sklearn-heart-disease.csv") pd.read_csv() reads the CSV file and creates a Pandas DataFrame.
Place the CSV in the same folder as your notebook (or update the path inside read_csv to match where you saved it).
Let's take a quick look at what we loaded:
heart_disease.head() You should see a table with columns like age, sex, chol, target, and so on. target is the column we'll try to predict — 1 means "has heart disease", 0 means "does not".
Check the size of the data:
Let's also check how many rows and columns we have:
heart_disease.shape This returns something like:
(rows, columns) For example:
(303, 14) would mean:
- 303 rows
- 14 columns
Check for missing values:
heart_disease.isna().sum() isna() checks which values are missing. sum() counts them.
So:
heart_disease.isna().sum() answers:
"How many missing values does each column contain?"
4.1 Splitting into Features (X) and Labels (y)
-
X= the features / "the questions" — everything you use to make a prediction. -
y= the label / "the answer" — the thing you're trying to predict.
X = heart_disease.drop("target", axis=1) This creates X by dropping the target column. X now holds every other column — the features the model will learn from.
y = heart_disease["target"] This creates y as just the target column — the labels the model will try to predict.
That's the first step done. Next, we split both into training and test sets.
A concrete example
Suppose our data looks like this:
| Age | Cholesterol | Exercise | Disease |
|---|---|---|---|
| 50 | 220 | 2 | 1 |
| 35 | 180 | 5 | 0 |
| 62 | 250 | 1 | 1 |
We want to predict Disease. So:
X = data.drop("Disease", axis=1) # Age, Cholesterol, Exercise y = data["Disease"] # Disease The result is:
X: Age Cholesterol Exercise 50 220 2 35 180 5 62 250 1 y: 1 0 1 A useful way to remember this:
X tells the model what it can look at.
y tells the model what answer it should learn to predict.
🧠 Vocabulary check
You'll see different names for these throughout ML documentation.
| Symbol | Also called |
|---|---|
X | Features, feature matrix, input data, independent variables |
y | Labels, targets, target variable, dependent variable, answer |
These terms refer to the same basic concepts. Get comfortable with them.
4.2 Splitting into training and test sets
You never want to evaluate a model on data it has already memorized — that tells you nothing about how it performs on new, real-world data. So you hold back a chunk of data purely for testing.
First, import the splitter:
from sklearn.model_selection import train_test_split This imports Scikit-Learn's tool for splitting data.
Now use it:
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1 ) Here's what just happened:
- We gave
train_test_splitour featuresXand our labelsy. - It returned four things, in this exact order:
-
X_train→ features used for training -
X_test→ features used for testing -
y_train→ correct answers for training -
y_test→ correct answers for testing
-
-
test_size=0.2→ means 20% of the data is held back for testing. -
random_state=1→ makes the split reproducible — same shuffle every run.
Let's confirm the split:
X_train.shape, X_test.shape, y_train.shape, y_test.shape You should see the training set is about 80% of the rows, and the test set is about 20%.
🧠 Mental model: the exam
Imagine studying for an exam.
-
X_train/y_trainare the practice questions with answers you study from. -
X_test/y_testare the real exam questions — you must not have seen these answers beforehand, or your "score" is meaningless.
If you trained on the test set, you'd be grading your own exam with the answer key open — you'd get a great score and learn nothing about how you'd actually perform.
What does random_state=1 mean?
train_test_split() randomly chooses which rows go into each set. If those rows change, your model's score can also change slightly. random_state=1 makes the random split repeatable.
So every time you run the code, you get the same split. The actual number doesn't matter.
These are all valid:
random_state=1 random_state=42 random_state=123 The important thing is using a fixed value when you want reproducible results.
Common test sizes
test_size | When to use |
|---|---|
0.2 (20%) | Default for most datasets |
0.1 (10%) | Very large datasets (millions of rows) |
0.3 (30%) | Very small datasets (hundreds of rows) — you want more evaluation confidence |
These aren't strict rules. The right split depends on the amount and type of data you have.
4.3 Making sure everything is numerical (Feature Encoding)
Most traditional Scikit-Learn models expect their input data to be numbers.
Let's first check the data types of our columns:
heart_disease.dtypes If every column shows int64 or float64, you’re okay. If you see object, that column probably contains text and needs to be converted into numbers.
Our heart disease dataset is already numerical, so for this section we'll use a car sales dataset that contains some actual text columns.
Real-world datasets often contain categorical values such as: "Make": "Toyota" or "Colour": "Blue".
Scikit-Learn models generally cannot use these text values directly. We need to convert them into numbers first.
This process is called feature encoding.
🔹 Why not simply assign numbers?
You might think:
"Toyota = 1, Honda = 2, BMW = 3. Done!"
The problem is that these numbers can make the model think there is an order or distance between the categories.
For example:
BMW = 3 Honda = 2 Toyota = 1 This could make the model think:
- BMW > Honda > Toyota
- BMW is "one unit" away from Honda
- Honda is "one unit" away from Toyota
But these relationships don't actually exist. BMW isn't mathematically greater than Honda, for example.
This is especially important for models such as linear models, SVMs, KNN, and neural networks, because they treat these numbers as real numerical values.
For categories without a natural order, called nominal categories, we usually use one-hot encoding instead.
📝 Two exceptions worth knowing:
- Ordinal categories have a natural order, such as
Small < Medium < LargeorPoor < Good < Excellent. In this case, integer values can represent the order. We can useOrdinalEncoderand explicitly define the order when needed.- Tree-based models such as decision trees, random forests and gradient boosting split values using thresholds, so they can handle integer-coded categories better than many other models. However, one-hot encoding is still a safe general-purpose choice.
🔹 One-Hot Encoding
One-hot encoding creates a separate column for each category.
Each column contains either:
0 = category does not apply 1 = category applies For example:
Colour → Blue Green Red Red 0 0 1 Blue 1 0 0 Green 0 1 0 Each category gets its own position, so there is no artificial ordering between categories.
📖 Worked example
One-hot encoding can also be used for words.
Suppose we have:
Corpus: ["cats like milk", "dogs like milk", "cats eat fish", "dogs eat fish"] The unique words are:
Vocabulary: [cats, dogs, like, milk, eat, fish] There are 6 unique words, so each word gets a vector with 6 positions:
cats → [1, 0, 0, 0, 0, 0] dogs → [0, 1, 0, 0, 0, 0] like → [0, 0, 1, 0, 0, 0] milk → [0, 0, 0, 1, 0, 0] eat → [0, 0, 0, 0, 1, 0] fish → [0, 0, 0, 0, 0, 1] Notice that "cats" and "dogs" are simply represented by different positions.
One-hot encoding does not understand that cats and dogs are both animals or that they are semantically related. It only tells the model that they are different categories.
This is one reason techniques such as Word2Vec and BERT embeddings are useful for text: embeddings can represent relationships and meaning, while one-hot encoding cannot.
If we add the one-hot vectors for all the words in:
"cats like milk" we get:
[1, 0, 1, 1, 0, 0] Tabular example
For a car dataset:
Colour (input) → Colour_Blue Colour_Green Colour_Red ---------------- ----------- ------------ ---------- Red 0 0 1 Blue 1 0 0 Green 0 1 0 Each category gets its own feature. There is no artificial ordering between Red, Blue and Green.
By default, Scikit-Learn sorts the categories, which is why the columns appear as:
Blue, Green, Red 🔹 In practice, with tabular data
For tabular data, Scikit-Learn provides OneHotEncoder.
First, load the data and separate the features (X) from the target (y):
import pandas as pd car_sales = pd.read_csv("sklearn-car-sales.csv") X = car_sales.drop("Price", axis=1) y = car_sales["Price"] Split before encoding
We should split our data before fitting the encoder.
Why?
Because the encoder learns which categories exist in the data when we call fit().
If we fit it using the entire dataset, it can learn information from the test set. This is a form of data leakage.
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1 ) Now we have:
Training data → used to learn Test data → used only for evaluation Now let's create our encoder:
from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer # Pick which columns to encode categorical_features = ["Make", "Colour", "Doors"] one_hot = OneHotEncoder(handle_unknown="ignore") transformer = ColumnTransformer( [("one_hot", one_hot, categorical_features)], remainder="passthrough" ) 📝 Note:
Doorsis stored as a number (3, 4, 5), but we treat it as a category here.A 3-door and a 5-door car are different kinds of car, and treating it as categorical stops the model assuming the effect grows in a straight line with the number of doors.
This is a judgement call: the values do have an order, so numeric is also defensible.
Here’s what each piece does:
-
OneHotEncoder(handle_unknown="ignore")creates the encoder (more onhandle_unknownbelow). -
ColumnTransformerapplies a transformation to specific columns and leaves everything else alone. -
[("one_hot", one_hot, categorical_features)]is a list of transformations. Each one is a tuple:(name, transformer, columns). Here it means: “applyone_hottocategorical_features, and call this stepone_hot.” -
remainder="passthrough"keeps the untouched columns as they are.
Now we fit the encoder using only the training data:
X_train_enc = transformer.fit_transform(X_train) fit_transform() does two things:
- Learns the categories from the training data.
- Converts the training data into encoded numerical data.
For the test data, we only use transform():
X_test_enc = transformer.transform(X_test) This uses the same categories learned from the training data.
We don't fit the encoder again on the test data.
The result is a numerical array where:
- categorical columns have been converted into one-hot columns
- numerical columns remain unchanged
If the encoded data contains many zeros, Scikit-Learn may store it as a sparse matrix to save memory. Many Scikit-Learn models can work with sparse matrices directly.
| Method | What it does |
|---|---|
fit() | Learns information from the data |
transform() | Converts data using what was learned |
fit_transform() | Learns and converts in one step |
A simple way to remember this is:
fit() → Learn transform() → Use what was learned fit_transform() → Learn + transform 🔹 A pandas shortcut
For quick exploration, pandas provides:
dummies = pd.get_dummies( car_sales[["Make", "Colour", "Doors"]], dtype=float ) pd.get_dummies does the same one-hot expansion but returns a pandas DataFrame.
A simple rule:
pd.get_dummies()is convenient for exploration.
OneHotEncoderis usually a better choice when building Scikit-Learn pipelines.
The reason: get_dummies doesn’t remember which categories it saw.
If the training and test sets contain different categories, you end up with different columns in each.
OneHotEncoder remembers its categories after fit() and applies them consistently.
🔹 Fit a model on the encoded data
Once our categorical values have been converted into numbers, we can give the data to a model.
from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() model.fit(X_train_enc, y_train) model.score(X_test_enc, y_test) Here’s what each piece does:
-
RandomForestRegressor()creates the Random Forest model. -
train_test_split()(used earlier) splits the data into training and testing sets, withtest_size=0.2putting 20% in the test set andrandom_state=1making the split reproducible. -
model.fit(X_train_enc, y_train)trains the model. -
model.score(X_test_enc, y_test)evaluates the model on the test data and returns its R² score.
🔹 The handle_unknown gotcha
Because we fit the encoder on the training data only, the test set (or future data) can contain a category the encoder never saw.
By default, OneHotEncoder crashes in that case:
ValueError: Found unknown categories ['Ferrari'] in column 0 during transform Fix it with:
one_hot = OneHotEncoder(handle_unknown="ignore") Now unseen categories produce a row of zeros instead of crashing. This is critical for production systems where new categories appear over time.
Key idea: Machine learning models generally need numerical input. For categorical features without a natural order, one-hot encoding converts each category into its own numerical feature. With Scikit-Learn, fit the encoder on the training data and use the learned encoder to transform validation or test data.
4.4 Handling missing values
Real-world data often contains missing values. Many ML models cannot work directly with missing values, so we need to decide what to do with them.
There are two common choices:
- Fill the missing values (called imputation).
- Drop the rows/col...
原文:https://www.a8q9.cn/en/article/machine-learning-with-scikit-learn-step-by-step-30ee9f.html