Skip to main content
This example demonstrates a complete Machine Learning workflow using Scikit-learn. It covers loading data, preprocessing, training, evaluation, saving the model, and making predictions.

Step 1: Import Required Libraries

Each import has a specific purpose.

Step 2: Load the Dataset

This loads the Iris dataset into memory. Think of iris as a Python object containing everything about the dataset. You can inspect it:
Output

Dataset Contents

Contains the feature values. Example There are 4 numerical features.
Contains the labels. Example
Where

Step 3: Separate Features and Labels

Machine Learning models always use:
Here,

Step 4: Split the Dataset

This divides the dataset into training and testing sets. Imagine you have 150 flowers.
Since
20% goes to testing.
Diagram

Why Split?

If we train and test on the same data:
Instead,

random_state=42

Makes the split reproducible. Without it, Run 1
Run 2
Every run changes. With 42, every run produces the same split.

Step 5: Create a Pipeline

This is one of the best features of Scikit-learn. Instead of writing
everything is combined into a single object. Pipeline structure

First Step

Standardizes every feature. Formula [
z=\frac{x-\mu}{\sigma}
]
Example Original values
Scaled values
Now all features have
This helps many algorithms converge faster and prevents features with larger scales from dominating.

Second Step

This is the Machine Learning algorithm. Its job:

Step 6: Train the Pipeline

This is the most important step. Internally, the pipeline performs:

Step A

Calculates
using only the training data.

Step B

Converts the training data into standardized values.

Step C

Learns the relationship
So the pipeline effectively does:
All with one line:

Step 7: Predict

The pipeline automatically:
Notice that it does not call fit() on the scaler again. It reuses the mean and standard deviation learned from the training data. Example output
Meaning

Step 8: Evaluate

For LogisticRegression, .score() returns accuracy. Internally it is equivalent to:
Suppose
Accuracy

Step 9: Save the Model

This saves the entire pipeline to a file.
contains:
  • StandardScaler (with learned mean and standard deviation)
  • LogisticRegression (with learned coefficients)
You don’t need to retrain the model every time you run your application.

Step 10: Load the Saved Model

This restores the saved pipeline into memory. It is identical to the original trained pipeline.

Step 11: Predict Again

Here,
selects the first five test samples. For example:
These samples are automatically:
Possible output

What Happens Internally?

Why use a Pipeline?

Without a pipeline, you’d manually write:
With a pipeline:
The pipeline automatically ensures that preprocessing is applied consistently during both training and prediction, making the code cleaner and reducing the risk of mistakes such as accidentally fitting the scaler on the test data.