Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Machine Learning
  • Supervised Learning: Features, Labels, Classification and Regression
  • NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      • Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
      • Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
      • Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
      • Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
      • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
      • Recommendations, Part 1: Two Stages, Candidates Then Ranking
      • Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
      • Recommendations, Part 2: Candidate Generation With Embeddings
      • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
      • Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
      • Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
      • Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
      • Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
      • Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
      • Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
      • Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
      • The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
      • The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
      • From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
      • The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
      • ML System Design Interview: Fraud Detection for Card Payments, in Eight Steps with Numbers
      • ML System Design Interview: A Recommendation Feed, From a Score to Beat to Online Guardrails
      • ML System Design Interview: Ad Click Prediction, Sparse Features, Calibration and Late Clicks
      • Interview Answer: How Do You Roll Out a New Model Safely When True Labels Come Weeks Later?
      • Mock ML Engineer Interview, Scored: A Rollout Question Where the Labels Arrive Weeks Late
      • The ML Coding Round: K-Means, Logistic Regression and a Top-k Metric From Scratch
      • The ML Depth Round: Five Questions That Always Come, in Thirty Seconds Each
      • Presenting Your Portfolio: A Six-Section README That Shows Evidence, Not Buzzwords
      • Reading a Job Ad and Shaping Your CV: A Gap List and CV Lines You Can Stand Behind
      • How AI Questions Show Up in an ML Engineer Interview: Your Angle, the Rounds and a Good Answer
      • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
      • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
      • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
      • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
      • Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place
      • Mock Interview, Scored: 429s at Peak Because One Customer's Batch Job Eats the Capacity
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. Foundations

      Supervised Learning: Features, Labels, Classification and Regression

      What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.

      Chaand Sheikh

      ·27 November 2026Foundations

      What you will learn

      • Explain supervised learning with features, labels, a model and a prediction
      • Tell a classification problem from a regression problem
      • Say why a hidden test set matters
      • Train a tiny ticket classifier with fit, then read predict and predict_proba

      Before you start

      • Basic Python

      Imagine you run a support inbox. Every day new tickets arrive, and each one has to reach the right team. There are two queues: billing, for charges, invoices and refunds, and technical, for crashes, logins and errors.

      Here's the useful part. The old tickets were already sorted by hand, so each one carries its right answer. Can a program learn from those old tickets? That question is what supervised learning is about, and we'll answer it with a twelve-ticket example from start to finish.

      Write rules, or learn from examples

      Think about how a small child learns fruit names. You show a card with an apple and say "apple". A banana, "banana". Another apple. Many times. Then you show a new picture, and the child names it.

      There are two ways to sort tickets.

      • Option 1: write rules by hand. If the text has the word "refund", send it to billing. If it has "crash", send it to technical. That works until a customer writes "I want my money back". No rule matches, and the ticket is lost.
      • Option 2: learn from examples. Show the program many tickets, each with its label, and let it find the patterns by itself.

      Supervised learning is option 2: flash cards for a program. Examples with answers, and then a new case.

      Five words, one picture

      Training data, model, prediction training data features (text) label charged twice this month billing app crashes in settings technical refund not arrived yet billing ... 12 tickets model fit new ticket I need a refund for the extra charge prediction billing
      The five words: training data, features, label, model and prediction. "Supervised" just means the answers were given.
      1. Training data: a table of examples.
      2. Features: the inputs. Here, the ticket text.
      3. Label: the known answer next to each example, billing or technical.
      4. Model: the thing that learns which words go with which label.
      5. Prediction: what the model gives back for a new ticket it has never seen.

      Classification and regression

      Supervised learning comes in two kinds, depending on the answer you want.

      KindThe answer isExamples
      Classificationa categorya ticket is billing or technical; an email is spam or not spam; a photo shows a cat or a dog
      Regressiona numberhouse size predicts the price; shop visits predict next week's sales; engine hours predict a repair cost

      Our ticket sorter picks one of two names, so it's classification. A category answer is classification, a number answer is regression. (For a regression worked end to end, see Linear Regression in scikit-learn.)

      Keep some tickets hidden

      One more idea before the code, and it's an important one. Say we have twelve labelled tickets. We don't give all of them to the model.

      Training part and hidden test part training part: tickets with labels billingbillingbillingbilling technicaltechnicaltechnicaltechnical model learns test part: labels hidden ???? compare with true labels predictions
      Most tickets train the model. The rest form a test part with the labels hidden: the model predicts, then we compare with the true labels.

      Why bother? Because scoring well on tickets the model has already studied proves very little. A test set shows how it behaves on tickets it has never seen. Our first script below skips this step to keep the code short; how to split properly, with train_test_split, is the subject of Train-Test Split and Data Leakage.

      The training data in code

      The code uses scikit-learn, a popular Python library for machine learning. Twelve tickets, six billing and six technical, each one a pair: the text and its label.

      from sklearn.feature_extraction.text import CountVectorizer
      from sklearn.linear_model import LogisticRegression
      # Training data: ticket text (the input) and the known answer (the label)
      tickets = [
          ("I was charged twice this month", "billing"),
          ("Please send me the invoice for March", "billing"),
          ("My refund has not arrived yet", "billing"),
          ("Update the card on my payment method", "billing"),
          ("Why did the price of my plan go up", "billing"),
          ("Cancel my subscription and stop billing", "billing"),
          ("The app crashes when I open settings", "technical"),
          ("I cannot log in, the page keeps loading", "technical"),
          ("Error message appears when I upload a file", "technical"),
          ("The website is very slow today", "technical"),
          ("Password reset email never shows up", "technical"),
          ("Sync stopped working on my phone", "technical"),
      ]
      texts = [text for text, label in tickets]
      labels = [label for text, label in tickets]

      The last two lines split the pairs into two lists. texts holds the inputs, labels holds the answers.

      Words become numbers, then fit

      The model can't read words directly. It needs numbers.

      # Turn each text into word counts (the features), then learn from the examples
      vectorizer = CountVectorizer()
      features = vectorizer.fit_transform(texts)
      model = LogisticRegression()
      model.fit(features, labels)

      CountVectorizer turns each text into word counts. Take the first ticket, "I was charged twice this month": was, charged, twice, this and month each get a count of 1. The single letter "I" is skipped; that's the default. fit_transform does this for all twelve tickets and gives a grid of 12 rows and 65 columns, one column for every word it has seen. Those counts are our features. (Bag of Words with CountVectorizer covers this step in depth.)

      Then we create a LogisticRegression model and call fit with the features and the labels. Fit is where the learning happens. Words like charged, month and twice end up leaning billing; sync, stopped and phone lean technical.

      And here's a surprise: the word my leans billing too. Four billing tickets say "my", and only one technical ticket does. The model only knows the examples we gave it.

      Three tickets it has never seen

      # New tickets the model has never seen
      new_tickets = [
          "I need a refund for the extra charge",
          "The app crashes on my phone",
          "My invoice shows the wrong price",
      ]
      predictions = model.predict(vectorizer.transform(new_tickets))
      for text, answer in zip(new_tickets, predictions):
          print(f"{answer:<10} <- {text}")
      billing    <- I need a refund for the extra charge
      technical  <- The app crashes on my phone
      billing    <- My invoice shows the wrong price

      Notice the new tickets get vectorizer.transform, not fit_transform: they're turned into counts with the same 65 columns the model learned from. Three tickets it has never seen, three labels, and all three are right.

      How sure is it? predict_proba

      So why these labels? Add a few lines after the script and ask the model how sure it is. predict_proba returns one probability per class, in the order of model.classes_.

      print(model.classes_)
      probabilities = model.predict_proba(vectorizer.transform(new_tickets))
      for text, probs in zip(new_tickets, probabilities):
          print(probs.round(2), text)
      ['billing' 'technical']
      [0.56 0.44] I need a refund for the extra charge
      [0.4 0.6] The app crashes on my phone
      [0.64 0.36] My invoice shows the wrong price
      How sure the model is on each new ticket 0 0.5 1.0 refund ... extra charge 3 of 6 words new 0.56 billing app crashes on my phone no new words 0.60 technical invoice ... wrong price 1 of 6 words new 0.64 billing
      The winning probability for each new ticket. All three are past 0.5 (red line), but none by much: twelve examples make a model that is right, but only just sure.
      • "I need a refund for the extra charge": it knows refund, for and the, but need, extra and charge are new. It only ever saw charged, with a d. Billing, at 0.56.
      • "The app crashes on my phone": no new words at all. App, crashes and phone all came from technical examples. Technical, at 0.6.
      • "My invoice shows the wrong price": it knows invoice, price and my; only wrong is new. Billing, at 0.64.

      All three are right, but only just. We gave it twelve examples, and more examples give better answers. For more on reading predict, predict_proba and classes_ together, see Logistic Regression in scikit-learn.

      Where it fits in AI engineering

      • Routing. A small classifier can decide where a request goes before any large model is called.
      • Evaluation. Labelled examples and a test set tell you whether a change made your system better or worse.
      • Checks. Classifiers can flag spam, unsafe text or the wrong topic around an AI feature.

      The idea is the same every time: examples with answers go in, and a model comes out. When you want a stronger ticket sorter with TF-IDF and a pipeline, the next step is Build a Text Classifier with TF-IDF and a Pipeline.

      Common mistakes

      • Calling a number problem classification, or the other way round. Ask: is the answer a category or a number?
      • Judging a model on the tickets it trained on. Only unseen data tells you the truth.
      • Calling fit_transform on new tickets. New data gets transform, so it uses the same columns as training.
      • Trusting a prediction without looking at how sure it is. 0.56 and 0.99 both print "billing".

      Quick recap

      WordMeaningIn the ticket sorter
      Featuresthe inputsword counts, a 12 x 65 grid
      Labelthe known answerbilling or technical
      Fitlearns from the examplesmodel.fit(features, labels)
      Classification / regressiona category answer / a number answerclassification
      Test setnew, unseen dataskipped here, see the split article

      Try it yourself

      Add the ticket "I want my money back" to new_tickets and run the script again. Then add two or three more labelled billing tickets that talk about money and see how predict_proba changes.

      Tried the exercise? Share your answer or ask a question.

      The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

      Join free on Skool

      Keep going in Machine Learning · 1 of 155

      Next post
      NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs

      Related course on Udemy

      Become an AI Engineer: LLMs, RAG, Agents and MCP

      Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

      Related posts

      NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs

      NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.

      On this page

      • Write rules, or learn from examples
      • Five words, one picture
      • Classification and regression
      • Keep some tickets hidden
      • The training data in code
      • Words become numbers, then fit
      • Three tickets it has never seen
      • How sure is it? predict_proba
      • Where it fits in AI engineering
      • Common mistakes
      • Quick recap
      • Try it yourself
      Community · Free to join
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool

      Related course on Udemy

      Become an AI Engineer: LLMs, RAG, Agents and MCP

      Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.