FREE Live Master Session: Code Your AI Companion for Kids

    Register for Free →
    AI & ML WorksheetsAI with Python
    Free Interactive Worksheet · Beginner

    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

    📊 Dataset (X, y)
    ✂️ Split Data
    🧠 Train Model (.fit)
    🎯 Predict (.predict)
    📈 Measure Accuracy

    # 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:

    🗄️ 1. Dataset (X & y)Hide ▲

    Stores input features matrix (X) and target class labels (y).

    X = [[2, 60], [8, 95]] y = [0, 1]

    💡 Remember: X is 2D matrix of features; y is 1D vector of target labels.

    🧠 2. fit(X_train, y_train)Inspect ▼

    Trains the model by fitting parameters to training data.

    🎯 3. predict(X_test)Inspect ▼

    Generates predicted class labels for new test features.

    📈 4. accuracy_score()Inspect ▼

    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:

    python_knn_pipeline.py
    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

    Python ScriptEditable
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    Execution Debugger & Timeline

    Click Run Code to record a step-by-step Python execution timeline.

    Variable Inspector

    No variables yet.

    Run your Python code to see them appear here live!

    Output & Console
    Output Console
    Press Run Code above to see Python output here.
    Real Python Execution & Tracing
    Interactive input() Supported
    💻

    Coding Exercises

    Interactive Python Missions

    1

    Data Scientist Setup

    BEGINNER · +15 XP

    Python Code Playground

    Ready to run

    Coding Mission 1 of 1BEGINNER

    Data Scientist Setup

    0 / 15 XP
    MISSION OBJECTIVE

    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.

    Mission Requirements
    Create variable X (features list)
    Create variable y (labels list)
    Print 4 (length of X)
    Python ScriptEditable
    1
    2
    3
    4
    5
    6
    Execution Debugger & Timeline

    Click Run Code to record a step-by-step Python execution timeline.

    Variable Inspector

    No variables yet.

    Run your Python code to see them appear here live!

    Output & Console
    Output Console
    Press Run Code above to see Python output here.
    Real Python Execution & Tracing
    Interactive input() Supported
    2

    Find the Nearest Neighbour

    BEGINNER · +20 XP

    Python Code Playground

    Ready to run

    Coding Mission 1 of 1BEGINNER

    Find the Nearest Neighbour

    0 / 20 XP
    MISSION OBJECTIVE

    Calculate distances between a new data point and 5 training examples. Use min() to find the nearest distance and print it.

    Mission Requirements
    Create distances list
    Create nearest variable using min()
    Print 0.9 (minimum distance)
    Python ScriptEditable
    1
    2
    3
    4
    5
    Execution Debugger & Timeline

    Click Run Code to record a step-by-step Python execution timeline.

    Variable Inspector

    No variables yet.

    Run your Python code to see them appear here live!

    Output & Console
    Output Console
    Press Run Code above to see Python output here.
    Real Python Execution & Tracing
    Interactive input() Supported
    3

    Accuracy Calculator

    INTERMEDIATE · +25 XP

    Python Code Playground

    Ready to run

    Coding Mission 1 of 1INTERMEDIATE

    Accuracy Calculator

    0 / 25 XP
    MISSION OBJECTIVE

    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.

    Mission Requirements
    Calculate correct predictions
    Calculate accuracy percentage
    Print 80 (accuracy percentage)
    Python ScriptEditable
    1
    2
    3
    4
    5
    6
    7
    8
    Execution Debugger & Timeline

    Click Run Code to record a step-by-step Python execution timeline.

    Variable Inspector

    No variables yet.

    Run your Python code to see them appear here live!

    Output & Console
    Output Console
    Press Run Code above to see Python output here.
    Real Python Execution & Tracing
    Interactive input() Supported
    4

    Feature Engineer

    INTERMEDIATE · +30 XP

    Python Code Playground

    Ready to run

    Coding Mission 1 of 1INTERMEDIATE

    Feature Engineer

    0 / 30 XP
    MISSION OBJECTIVE

    Create a dictionary called student with keys: name, study_hours, attendance_pct. Print key and value using a loop.

    Mission Requirements
    Create student dictionary
    Print Alex in output
    Python ScriptEditable
    1
    2
    3
    4
    5
    6
    7
    8
    9
    Execution Debugger & Timeline

    Click Run Code to record a step-by-step Python execution timeline.

    Variable Inspector

    No variables yet.

    Run your Python code to see them appear here live!

    Output & Console
    Output Console
    Press Run Code above to see Python output here.
    Real Python Execution & Tracing
    Interactive input() Supported
    🧠

    Knowledge Check

    Ready to test your knowledge?

    Answer 10 multiple-choice questions to test your understanding of scikit-learn, fit/predict, KNN, and accuracy!

    🚀 Ready for live coding?

    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.