Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course

4.1 Machine Learning Basics: Learning from Data, Features and Train-Test Split

Unit 4 – Data and Analysis · 90 min read · 9 MCQs to check yourself

Train, test and validation sets explained

1. Machine learning vs rule-based algorithms

Rule-based (traditional) Machine learning
Humans write the rules: if temperature > 38: "fever" The algorithm learns rules/patterns from examples
Works when rules are clear and few Works when rules are too complex to write (faces, speech, spam, fraud)
Easy to explain; does not improve by itself Improves with more and better data; may be hard to explain
Fails on situations the programmer did not think of Can generalise to new, unseen examples – if trained well

Example – spam filter: a rule-based filter blocks e-mails containing “lottery”; spammers write “l0ttery”. An ML filter learns from thousands of labelled spam/not-spam e-mails and catches new tricks.

2. How “learning from data” works

  1. Give the algorithm many examples: each has features (inputs, X) and, for supervised learning, a label (correct answer, y).
  2. The algorithm adjusts its internal parameters to make its predictions as close as possible to the labels (it minimises an error/loss).
  3. The trained model is then used to predict labels for new data.
Type Data Goal Algorithms Example
Regression (supervised) labelled, numeric target predict a number linear regression, decision tree regressor predict a house price or exam marks
Classification (supervised) labelled, category target predict a class logistic regression, decision tree, KNN, neural network spam / not spam, pass / fail, disease / healthy
Clustering (unsupervised) no labels find groups K-means group customers by buying habits

Which algorithm fits which data structure? Tables of numbers (rows = examples, columns = features) suit regression, trees and KNN; images (grids of pixels) suit convolutional neural networks; text and speech (sequences) suit language models/RNNs; graphs (networks of friends) suit graph algorithms.

3. Model building step by step

Feature engineering – choosing, creating and transforming input features so the model can learn better:

Good features often matter more than the choice of algorithm.

Train-test split – divide labelled data, e.g. 80% training and 20% testing. The model learns only from the training set; the test set is kept hidden and used to check how well the model works on new, unseen data. Testing on the training data would be like giving students the exact exam questions in advance – a high score proves memorisation, not learning.

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

hours = [[1], [2], [2.5], [3], [4], [4.5], [5], [6], [6.5], [7]]      # feature
marks = [35, 45, 48, 55, 62, 66, 70, 80, 82, 88]                     # label
X_train, X_test, y_train, y_test = train_test_split(hours, marks, test_size=0.2, random_state=1)
model = LinearRegression().fit(X_train, y_train)

print("trained on", len(X_train), "students, tested on", len(X_test))
print("marks increase per extra hour:", round(model.coef_[0], 1))
print("predicted marks for 5.5 hours:", round(model.predict([[5.5]])[0]))
print("R² on the unseen test data:", round(model.score(X_test, y_test), 3))

Output:

trained on 8 students, tested on 2
marks increase per extra hour: 8.5
predicted marks for 5.5 hours: 75
R² on the unseen test data: 0.998

Model assessment – measure performance on the test set with metrics (next lesson) and compare with a simple baseline (e.g. always predicting the average).

4. Prediction is not causation

A model can predict well from a feature that does not cause the outcome.

To show causation we need controlled experiments (randomly assign groups, change one thing) – the topic of hypothesis testing (lesson 4.4).

Short and long questions

1. A bank wants to use machine learning to predict whether a loan applicant will repay the loan. Explain how “learning from data” works and describe the stages of building this model, including feature engineering, train-test split and model assessment. Also explain why the model’s predictions should not be treated as causes. (2 + 3 + 1)

Model answer

Learning from data (2): the bank gives the algorithm thousands of past applications; each has features (income, existing loans, job type, repayment history, age) and a label (repaid / defaulted). The algorithm adjusts its parameters to reduce prediction errors and learns patterns that link features to the label. This is supervised classification.

Stages (3):

  1. Collect and clean data – remove duplicates, fill missing incomes.
  2. Feature engineering – create debt_to_income = monthly_debt / income, encode job type and city as numbers, scale amounts; drop irrelevant fields like application ID.
  3. Train-test split – e.g. 80% of applications to train, 20% kept unseen.
  4. Train a model (logistic regression or decision tree).
  5. Assess on the test set with accuracy, precision and recall (missing defaulters is costly), compare with a baseline, tune hyperparameters and retrain.
  6. Deploy and monitor for fairness and changing patterns.

Prediction vs causation (1): the model may find that applicants from a certain area default more often; living there does not cause default – income or other hidden factors may. Treating predictions as causes can lead to unfair, discriminatory decisions.

2. Classify each problem as regression, classification or clustering: (a) predict house prices, (b) detect fraudulent transactions, (c) group news articles by topic without labels.

Model answer

(a) Regression – the output is a number (price). (b) Classification – fraud / not fraud. (c) Clustering – unsupervised grouping without labels.

3. Explain the difference between prediction and causation with an example.

Model answer

Prediction means one variable helps forecast another because they are correlated. Causation means changing one variable actually changes the other. Example: ice-cream sales predict drowning numbers, but ice-cream does not cause drowning – hot weather causes both. Causation needs controlled experiments.

4. What are the key steps involved in building a machine-learning model?

Model answer
  1. Define the problem and collect/clean data. 2. Feature engineering (select, create, encode, scale). 3. Train-test split. 4. Choose and train an algorithm on the training set. 5. Evaluate on the test set with suitable metrics. 6. Tune hyperparameters and improve, then deploy and monitor.

5. Differentiate between machine learning and rule-based algorithms with one example each.

Model answer
Rule-based Machine learning
Programmer writes explicit rules Algorithm learns patterns from data
Good for clear, fixed logic Good for complex patterns
Does not improve with data Improves with more data
Example: grade = "A" if marks ≥ 80 Example: spam filter learning from labelled e-mails

6. What is feature engineering, and why is it important in machine learning? (1 + 2)

Model answer

Feature engineering is selecting, creating and transforming input variables (features) so a model can learn effectively (1). Importance (2): better features give more accurate and simpler models – often more than changing the algorithm; it removes irrelevant/noisy inputs, handles missing values and converts data (dates, categories) into forms the algorithm can use. Example: price_per_sq_ft from price and area helps predict house value.

7. What is the purpose of the train-test split in machine-learning model building?

Model answer

The labelled data is divided (e.g. 80% training, 20% testing). The model learns only from the training set; the test set is kept unseen and used to evaluate how well the model performs on new data. This detects overfitting (memorising) and gives an honest estimate of real-world accuracy.

This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Unit 3 Review, Situational Quiz and Unit Test · Next: 4.2 Evaluating Models: Confusion Matrix, Metrics and Hyperparameter Tuning

All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course