AI with PythonWorksheet 11 · Scikit-Learn & KNN Pipeline
Write real Python Machine Learning code! Learn scikit-learn, split datasets, fit KNN models, make predictions, and measure accuracy!
Overview
Python Machine Learning with scikit-learn
scikit-learn (sklearn) is Python's most popular Machine Learning library. It provides ready-to-use algorithms for classification, regression, and clustering so developers don't need to write ML math from scratch!
Visual ML Pipeline
# Importing scikit-learn KNN in Python:
from sklearn.neighbors import KNeighborsClassifier
Scikit-learn Power: Used by tech leaders worldwide to build predictive AI models in Python with under 15 lines of code!
Scikit-Learn Core Concepts
Click each card to inspect
Every scikit-learn classification pipeline relies on four core concepts. Click each card to learn more:
Stores input features matrix (X) and target class labels (y).
💡 Remember: X is 2D matrix of features; y is 1D vector of target labels.
Trains the model by fitting parameters to training data.
Generates predicted class labels for new test features.
Compares true test labels against predicted labels.
🌸 The Iris Benchmark Dataset
Included directly inside sklearn.datasets.load_iris(). It contains 150 flower samples with 4 features (sepal/petal lengths & widths) and 3 species targets (Setosa, Versicolor, Virginica).
Fit & Predict
The Full Python Scikit-Learn Pipeline
Here is the complete, standard Python code used in real data science to train a K-Nearest Neighbours (KNN) classifier:
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 1. Load dataset
iris = load_iris()
X = iris.data # 150 rows x 4 feature matrix
y = iris.target # 150 class labels (0, 1, 2)
# 2. Split data (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 3. Create & Train KNN Classifier (K=3)
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
# 4. Predict & Evaluate Accuracy
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))Playground: Toy KNN Simulator
Pure Python KNN Logic
Run simplified KNN distance math in pure Python right in your browser! Edit variables, run code, and click Explain Code:
Python Code Playground
Ready to run
No variables yet.
Run your Python code to see them appear here live!
Click Run Code to record a step-by-step Python execution timeline.
No variables yet.
Run your Python code to see them appear here live!
Coding Exercises
Interactive Python Missions
Data Scientist Setup
Python Code Playground
Ready to run
Data Scientist Setup
Create X as a list of 4 student feature records ([study_hours, attendance_pct]). Create y as pass/fail labels (1=Pass, 0=Fail). Print the length of X.
No variables yet.
Run your Python code to see them appear here live!
Click Run Code to record a step-by-step Python execution timeline.
No variables yet.
Run your Python code to see them appear here live!
Find the Nearest Neighbour
Python Code Playground
Ready to run
Find the Nearest Neighbour
Calculate distances between a new data point and 5 training examples. Use min() to find the nearest distance and print it.
No variables yet.
Run your Python code to see them appear here live!
Click Run Code to record a step-by-step Python execution timeline.
No variables yet.
Run your Python code to see them appear here live!
Accuracy Calculator
Python Code Playground
Ready to run
Accuracy Calculator
Given y_test=[1,0,1,1,0] and y_pred=[1,0,0,1,0], count correct predictions, divide by total, and print accuracy percentage.
No variables yet.
Run your Python code to see them appear here live!
Click Run Code to record a step-by-step Python execution timeline.
No variables yet.
Run your Python code to see them appear here live!
Feature Engineer
Python Code Playground
Ready to run
Feature Engineer
Create a dictionary called student with keys: name, study_hours, attendance_pct. Print key and value using a loop.
No variables yet.
Run your Python code to see them appear here live!
Click Run Code to record a step-by-step Python execution timeline.
No variables yet.
Run your Python code to see them appear here live!
Knowledge Check
Ready to test your knowledge?
Answer 10 multiple-choice questions to test your understanding of scikit-learn, fit/predict, KNN, and accuracy!
Build Real Machine Learning Models with Tutors
Take the next step! Join our live Intro to Machine Learning Course and write real Python ML code with expert 1-on-1 guidance.