Data and analysis
This unit is about turning data into decisions. It starts with the types of data and how machine learning models learn from data: building a model, splitting data for training and testing, avoiding overfitting and underfitting, and measuring performance with accuracy, precision, recall and F1 score. It then shows how to present data clearly with charts, stories and dashboards, how to summarise it with descriptive statistics, and how to check a claim with hypothesis testing using null and alternative hypotheses, p-values and significance levels.
Learning outcomes (12)
- Differentiate between machine learning models and rule-based algorithms, with their advantages and limitations.
- Describe the process of model building in machine learning: data collection, preprocessing, feature engineering, training, evaluation and deployment.
- Explain feature engineering, test-train split, training and test data, overfitting and underfitting.
- Differentiate between supervised, unsupervised and reinforcement learning.
- Assess a model using accuracy, precision, recall and F1 score.
- Explain how models learn from data and choose algorithms for structured and unstructured data.
- Differentiate between predictive and causal models and describe applications of machine learning.
- Use data visualization tools, including Python, to present data, and create a simple dashboard.
- Read, critique and create data stories judged by clarity, accuracy, relevance, insight and persuasion.
- Formulate questions, identify relevant data and evaluate data quality.
- Use descriptive statistics (mean, median, mode, range, variance, standard deviation) to summarise data.
- Formulate null and alternative hypotheses and explain p-values, significance testing and the steps of hypothesis testing.
IntroIntroduction: learning from data
You already know that a computer program follows instructions written by a programmer. Machine learning (ML) is a different idea: the computer learns from existing data to make new decisions. Nobody writes every rule. Instead, the computer is trained on examples and finds the pattern itself.
The book describes the process like this. Algorithms are designed with the help of raw data, and the data is turned into useful models. The models are tested (assessed) on their performance in different situations. During these assessments they learn patterns and improve. Once a model reaches a certain level of accuracy, it can predict future values from past data patterns. By studying the results of such models we can also understand cause-and-effect relationships in data. In this way data and computers let us look at likely future results based on existing data.
Example: email spam filter
A spam filter learns from the labels of past emails (spam or not spam). When we mark an email in our inbox as spam, the model learns the keywords used in that email. The next time an email arrives with similar words, the filter automatically sends it to the spam folder. Emails that do not look like spam go to the inbox.
4.1Data typesOften examined
Data is a collection of raw facts and figures collected from different sources. In data science and machine learning, data is grouped into types. The type of data decides how we store it, which chart shows it best and which algorithm can learn from it.
| Data type | Description | Examples |
|---|---|---|
| Numerical | Quantitative data used to represent numerical values (numbers you can measure or count). | Marks, salary, age |
| Categorical | Data that has discrete values (categories or labels). It is divided into nominal data and ordinal data. | Nominal: male, female, colour. Ordinal: rank, high, low, small, large |
| Boolean | Has only two possible values, 0 or 1. | True/False, Yes/No |
| Text data | Contains a sequence of characters. | Description, review, feedback |
| Time series | Collected over a long period of time, one value after another in time order. | Stock price, weather data |
| Image | Represented as pixel values in the image. | X-ray, ultrasound, photographs |
| Audio | In the form of sound waves. | Speech, music |
| Structured | Organised in the form of rows and columns (tables). | Spreadsheet, database |
| Semi-structured | Organised in some specific format, but there is no fixed pattern (schema). | XML, JSON files |
| Unstructured | Has no predefined structure. | Videos, emails, web pages |
Nominal and ordinal data
- Nominal data
- Categories that have names only and no natural order, for example gender (male, female) or colour (red, green, blue). We cannot say red is greater than blue.
- Ordinal data
- Categories that have a natural order or rank, for example small, medium, large or low, high, or position in class (1st, 2nd, 3rd). The order matters, but the gap between two levels is not a fixed number.
4.1.1Machine learning and rule-based algorithmsOften examined
Introduction to machine learning
Before the core ideas of machine learning, we need a few foundation topics: how models are trained, evaluated and improved using data, and the metrics (numbers) used to measure how well a model performs. These are the building blocks for the rest of the unit.
The difference
A machine learning model learns from data to make decisions. It adapts and improves over time as it processes more data. A rule-based algorithm follows fixed instructions (if this, then that) written by a person. It does not change unless we deliberately update the rules.
| Point | Machine learning model | Rule-based algorithm |
|---|---|---|
| How it works | Learns patterns from data | Follows fixed rules written by people |
| Change over time | Adapts and improves as it gets more data | Does not change unless rules are updated by hand |
| Problems handled | Complex problems, unexpected situations, unstructured data | Simple, well-defined problems where rules are known |
| Data needed | Large datasets; accuracy depends on dataset size | Works with limited data |
| Behaviour | Flexible and dynamic, can learn new things | Consistent: same input gives same output |
| Explaining decisions | Hard to interpret (complex decision-making) | Easy to follow and explain |
| Resources | Needs significant computing power | Needs fewer resources, easy to implement |
| Example | Spam filter that learns spam words | Rule: if subject contains "lottery", mark as spam |
Advantages of machine learning
- Handles complex and unstructured data (images, audio, text).
- Automatically learns patterns from data without explicit programming of every rule.
- Does not require expert knowledge or human intervention for every decision.
- Its accuracy improves as the dataset grows (accuracy depends on the size of the dataset).
Advantages of rule-based algorithms
- Do not require large datasets; work well with limited data because they depend on predefined rules.
- Performance is consistent for the same set of rules.
- Need fewer resources and can be implemented easily.
Limitations of machine learning
- Does not perform well if the data is too little.
- Its decision-making process is complex and cannot be easily interpreted.
- Requires significant computational resources.
- A model that is too complex can lead to overfitting.
- If the training data is biased, it can give wrong results.
Limitations of rule-based algorithms
- Limited flexibility: cannot adapt to new data that the rules did not expect.
- Can give wrong results if the data is unstructured or ambiguous.
- Cannot learn from data.
- If too many rules pile up, the system slows down and becomes hard to manage.
Seeing the difference in Python
The program below compares a fixed rule with a filter that learns spam words from four labelled emails. The new email does not contain the word "lottery", so the fixed rule misses it. The learned filter has seen the words "free" and "prize" in spam before, so it catches it.
# Rule-based spam check versus a filter that learns spam words from labelled emails
def rule_based(email):
# fixed rule written by a programmer
return "spam" if "lottery" in email.lower() else "inbox"
# labelled past emails (the training data)
past = [("Win a free prize now", "spam"),
("Claim your free gift", "spam"),
("Meeting at 10 am", "inbox"),
("Class test on Monday", "inbox")]
spam_words = set()
for text, label in past:
if label == "spam":
spam_words.update(text.lower().split())
for text, label in past:
if label == "inbox":
spam_words -= set(text.lower().split()) # keep words seen only in spam
def learned(email):
return "spam" if spam_words & set(email.lower().split()) else "inbox"
new_email = "Free prize waiting for you"
print("Rule-based:", rule_based(new_email))
print("Learned :", learned(new_email))Rule-based: inbox
Learned : spam4.1.2Model building in machine learningOften examined
Model building is the process of creating a mathematical or computational model that represents relationships between variables in data, so that it can make predictions or give insights. It has several key steps.
- Step 1: Data collection. Collect data from various sources, for example thousands of labelled images of dogs, cats and horses.
- Step 2: Data preprocessing (cleaning) and feature engineering. Make the data clean and suitable for analysis: normalise values (bring numbers to a similar scale), handle missing data, and encode categorical variables as numbers. Then choose and prepare the useful features.
- Step 3: Choose an algorithm and train the model. Select a suitable ML algorithm for the problem (classification, regression, clustering or another type). The algorithm is trained on the dataset, adjusting its parameters to reduce error and improve accuracy.
- Step 4: Evaluate the model. During training, performance is checked on a separate validation set to make sure the model is accurate on new, unseen data. When the model is optimised, it is tested on a final test dataset.
- Step 5: Deploy the model. If the results are satisfactory, the model is deployed for real-world use. Otherwise it needs further improvement.
Throughout this process, every time the model reads data and calculates results, the algorithm keeps learning. Repeated refinement and evaluation give a model that performs well and meets the needs of the application.
Key terms explained with one example
The book uses one real-life problem to explain each term: we want a model that can tell apart images of dogs, cats and horses. First we need a reasonable collection of images of all three animals.
- Feature engineering
- The process of selecting and transforming the most relevant data features to improve a model's performance. For the animal images we list common and distinct features of each animal: size, colour, appearance, shape of eyes, ears, hair, nose and so on. The model keeps data about all possible variations of these features, so that a sitting horse is not confused with a big standing dog.
- Test-train split
- Dividing the data into two parts: training data (the main, larger portion) and test data (the smaller portion). In the example a 70:30 split is used. The ratio must be chosen wisely: if we use too much data for training (leaving too little to check it), the model can overfit; if we give too little data for training, the model will underfit.
- Training data
- The main dataset used to teach a model to make predictions or decisions. If we have 100,000 images, we can give 60,000 to 70,000 images to the model to learn from. In supervised learning each picture carries its label: cat, dog or horse.
- Test data
- A small portion of data kept aside to evaluate the trained model. These images are not shown to the model during training; they come from the remaining 30 to 40 percent. We check whether the model gives the right answer for them.
- Model training
- The key step in which the model learns from the training data so that its decisions become accurate and meaningful. Without proper training the machine cannot decide about new data.
Test-train split in Python
The scikit-learn function does the split. keeps 30 percent for testing; fixes the shuffle so the result is the same every time.
# 70:30 test-train split of 10 labelled images
from sklearn.model_selection import train_test_split
images = ["img1", "img2", "img3", "img4", "img5",
"img6", "img7", "img8", "img9", "img10"]
labels = ["cat", "dog", "horse", "cat", "dog",
"horse", "cat", "dog", "horse", "cat"]
X_train, X_test, y_train, y_test = train_test_split(
images, labels, test_size=0.3, random_state=1)
print("Training images:", len(X_train))
print("Test images:", len(X_test))Training images: 7
Test images: 3Machine learning and human learning
Fig. 4.5 of the book compares the two. A machine learns from samples with labels (this picture: dog; this picture: cat). A human learns from examples (seeing dogs), descriptions or diagrams (a dog has long ears and a black nose) and comparisons (a dog next to a cat). A machine needs many more examples than a human to learn the same thing.
4.1.2Supervised, unsupervised and reinforcement learningOften examined
The book lists three commonly used ways a machine learning model is trained.
- Supervised learning
- The model is trained using labelled data, where the correct output is given for each input. Example algorithm: Linear Regression, used to predict continuous values such as prices or temperatures. Labelled animal photos used to train a cat, dog and horse classifier are also supervised learning.
- Unsupervised learning
- The data is unlabelled, and the model tries to find patterns or groupings on its own. Example algorithm: K-Means Clustering, which groups similar data points together, for example in customer segmentation.
- Reinforcement learning
- The model learns by interacting with an environment and receiving feedback in the form of rewards or penalties. Example algorithm: Q-Learning, often used in game playing or robotic navigation, where the model learns to make decisions that maximise its rewards.
| Point | Supervised | Unsupervised | Reinforcement |
|---|---|---|---|
| Data | Labelled (input with correct output) | Unlabelled | No fixed dataset; experience from the environment |
| Goal | Predict the label or value for new input | Discover hidden groups or patterns | Learn actions that earn the most reward |
| Feedback | Correct answer for every example | None | Reward or penalty after actions |
| Example algorithm | Linear regression, classification | K-Means clustering | Q-Learning |
| Example use | Predict house prices, classify emails | Customer segmentation | Game playing, robot navigation |
Regression, classification and clustering
- Regression algorithms predict continuous values such as prices or temperatures (supervised).
- Classification algorithms sort data into categories such as cat, dog or horse, or spam and not spam (supervised).
- Clustering algorithms group similar data points together without labels (unsupervised).
4.1.2Overfitting and underfittingOften examined
- Overfitting
- Happens when a machine learning model learns the training data too well, including its noise and irrelevant details. The model performs very well on the training data but poorly on new, unseen data, because it has become too specific to the training set.
- Underfitting
- Happens when a model is too simple and fails to capture the underlying pattern in the data. It performs poorly on both the training data and new data, because it has not learned enough.
| Point | Overfitting | Underfitting |
|---|---|---|
| Cause | Model too complex, or learns noise | Model too simple, or trained too little |
| Training data | Very high accuracy | Low accuracy |
| New (test) data | Low accuracy | Low accuracy |
| Analogy | A student who memorises past papers word for word and fails when the question changes | A student who studied too little and fails both easy and hard questions |
| Remedy | More training data, simpler model, remove irrelevant features | More complex model, better features, train longer |
4.1.2Model assessment: accuracy, precision, recall and F1 scoreOften examined
Model assessment evaluates a model's performance using measures such as accuracy, precision and recall. In the book's example we give the trained model 100 new images of cats, dogs and horses that were not part of its training or test data. If it labels 80 images correctly and 20 wrongly (for example it calls a dog a horse), its accuracy is 80 percent.
The four outcomes
Take the class "Cat" as the positive class. Every prediction falls into one of four boxes.
| Outcome | Meaning (class: Cat) |
|---|---|
| True Positive (TP) | Model predicts "Cat", and the actual animal is a cat. |
| False Positive (FP) | Model predicts "Cat", but the actual animal is a dog or horse. |
| True Negative (TN) | Model predicts "Not Cat", and the actual animal is a dog or horse. |
| False Negative (FN) | Model predicts "Not Cat", but the actual animal is a cat. |
The four measures
- Accuracy
- The percentage of all predictions that are correct. It tells how often the model is right overall.
- Precision
- Out of all the predictions the model made for a class (for example "positive"), how many are actually correct. It is about the quality of the positive predictions.
- Recall
- How well the model finds all the actual positive cases in the data. It shows the model's ability to find all the relevant instances.
- F1 score
- The harmonic mean of precision and recall. It balances the trade-off between the two and gives one score. It is very useful when the dataset is imbalanced.
- Accuracy uses all correct predictions (TP and TN) out of all 10.
- Precision looks only at the 6 images the model called Cat.
- Recall looks only at the 5 images that really are cats.
- F1 combines the two.
The same calculation in Python, starting from the actual and predicted labels:
# Accuracy, precision, recall and F1 score for the class "Cat"
actual = ["Cat", "Cat", "Dog", "Cat", "Horse", "Dog", "Cat", "Horse", "Dog", "Cat"]
predicted = ["Cat", "Dog", "Cat", "Cat", "Horse", "Dog", "Cat", "Cat", "Dog", "Cat"]
tp = fp = fn = tn = 0
for a, p in zip(actual, predicted):
if p == "Cat" and a == "Cat":
tp += 1 # said Cat, really Cat
elif p == "Cat" and a != "Cat":
fp += 1 # said Cat, but not a Cat
elif p != "Cat" and a == "Cat":
fn += 1 # missed a real Cat
else:
tn += 1 # said Not Cat, really Not Cat
correct = sum(1 for a, p in zip(actual, predicted) if a == p)
accuracy = correct / len(actual)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print("TP =", tp, " FP =", fp, " FN =", fn, " TN =", tn)
print("Accuracy =", round(accuracy, 2))
print("Precision =", round(precision, 2))
print("Recall =", round(recall, 2))
print("F1 score =", round(f1, 2))TP = 4 FP = 2 FN = 1 TN = 3
Accuracy = 0.7
Precision = 0.67
Recall = 0.8
F1 score = 0.734.1.3Learning from data
In machine learning, models find patterns in data. The more data the model has, the better it can learn. Models improve their performance based on feedback from the data, and learning from data helps them make accurate predictions.
- Different algorithms suit different data. Some algorithms work better with specific types of data.
- Learning means finding trends and patterns. As the model sees more examples, its performance improves.
- Data quality matters. If our dataset has very clear images of cats, dogs and horses, the model will learn well. Blurred, wrongly labelled or biased data teaches wrong patterns ("garbage in, garbage out").
- Continuous learning keeps the model accurate and improves its accuracy over time: the model keeps adapting as new data arrives, so it does not become out of date.
- Good data helps models learn and make better predictions.
Fig. 4.6 of the book shows the idea: a set of labelled images (cat, dog, dog, cat, cat, cat) is used to train the machine learning model. After training, the model receives a new picture and outputs "Cat" or "Dog".
4.1.4Algorithms for different data structures
Choosing the right algorithm for a machine learning model is very important. There are many algorithms, and some guidelines help us pick the one that gives the desired results. The first guideline is the type (structure) of the data.
| Point | Structured data | Unstructured data |
|---|---|---|
| Meaning | Organised in tables with rows and columns | Unorganised, no specific structure or predefined format |
| Search | Easily searchable and quantifiable | Hard to search directly |
| Examples | Databases, spreadsheets, CSV files | Text, images, audio and video files, social media posts, emails, sensor readings |
| Suitable algorithms | Traditional algorithms such as regression and classification | Advanced algorithms such as neural networks |
Matching the algorithm to the problem
- Supervised learning uses labelled data to train models.
- Unsupervised learning finds patterns in unlabelled data.
- Regression algorithms predict continuous values like prices.
- Classification algorithms sort data into categories.
- Clustering algorithms group similar data points together.
- Neural networks are used for complex patterns and large data.
For example, a collection of cat images has very complex patterns: colours, shapes, textures, the position of the cat and the angle of the picture. Neural networks can handle such patterns easily. Similarly, a very large dataset, such as all social media posts on COVID-19, has a huge number of items. Neural networks can be trained on many posts in parallel using powerful computers and GPUs (graphics processing units), so they suit such tasks.
4.2Data visualizationOften examined
Data visualization is the graphical representation of information and data. Using visual elements such as charts, graphs and maps, visualization tools give an easy way to see and understand trends, outliers and patterns in data. It also lets employees and business owners present data to non-technical audiences without confusion. (In Grade 11 we visualised the Tips dataset in Python.)
Tools for visualization
| Tool | What it does |
|---|---|
| SQL | A language that helps us get (query) data from databases before we chart it. |
| Python: Matplotlib and Seaborn | Libraries that create charts and graphs from code. |
| Python: Plotly and Dash | Interactive charts and web dashboards (section 4.3.6). |
| R | A special tool that is strong at statistical graphics and visualizations. |
Different tools suit different tasks and skill levels. Some tools let us interact with the data, which makes exploring it easier. The right choice depends on what we want to do with the data. Good visualization helps us tell a story with data so that others understand it.
Common visual elements (Fig. 4.7)
| Visual | Best used for |
|---|---|
| KPI (key performance indicator) | One big number showing a target or result, such as 100% or sales this month |
| Table | Exact values in rows and columns |
| Bar chart | Comparing values of different categories |
| Line chart | Change over time (trends) |
| Donut chart | Parts of a whole (shares or percentages) |
| Tree map | Parts of a whole shown as nested rectangles |
| Bullet chart | Progress of one value against a target |
| Scatter plot | Relationship between two numerical variables, and outliers |
| Geo map | Values by location (city, province, country) |
| Radial chart | Comparing several variables around a circle |
4.2.1Data visualization by using Python
The book's program (Fig. 4.8, run in Google Colab) uses three libraries. NumPy stores the numbers in arrays, Matplotlib (pyplot) draws the graph, and scikit-learn provides the LinearRegression model, which draws the best straight line through the points. The data is study hours (input) and marks obtained (output).
# Import numpy library and give it a short name 'np'
# We use numpy to create and manage arrays (tables of numbers)
import numpy as np
# Import the 'pyplot' part of matplotlib and give it a short name 'plt'
# We use 'pyplot' to make graphs like scatter plots and lines
import matplotlib.pyplot as plt
# Import the LinearRegression class from sklearn's linear_model module
# We use it to create a machine learning model that can draw a straight line through points
from sklearn.linear_model import LinearRegression
# Step 1: Prepare the data (study hours and marks)
X = np.array([[1], [2], [3], [4], [5]]) # Input: hours studied
y = np.array([10, 20, 30, 40, 50]) # Output: marks obtained
# Step 2: Create and train the Linear Regression model
model = LinearRegression()
model.fit(X, y)
# Step 3: Predict the marks based on study hours
y_pred = model.predict(X)
# Step 4: Plot the actual points and the prediction line
plt.scatter(X, y, color='blue') # Plot real data points in blue
plt.plot(X, y_pred, color='red') # Plot the prediction line in red
plt.title('Study Hours vs Marks') # Title of the graph
plt.xlabel('Hours Studied') # X-axis label
plt.ylabel('Marks Obtained') # Y-axis label
plt.show() # Show the final graphHow the program works
- Import libraries. as for arrays, as for graphs, and the class from .
- Step 1: prepare the data. holds hours as a 2-D array (one column), because scikit-learn expects inputs as rows and columns. holds the marks.
- Step 2: create and train the model. makes the model learn the relation between hours and marks (supervised learning, since each input has its correct output).
- Step 3: predict. gives the marks the model expects for each number of hours.
- Step 4: plot. draws the real points in blue, draws the prediction line in red, and , , add labels. displays the graph.
The graph itself cannot be printed as text, so the version below prints what the model learned. The slope 10 means every extra hour adds 10 marks; the intercept 0 means zero hours gives zero marks. The model can now predict marks for a new input such as 6 hours.
# Train a Linear Regression model on study hours and marks, then print its predictions
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]]) # input: hours studied
y = np.array([10, 20, 30, 40, 50]) # output: marks obtained
model = LinearRegression()
model.fit(X, y) # the model learns the pattern from the data
print("Slope:", round(model.coef_[0], 2))
print("Intercept:", round(model.intercept_, 2))
y_pred = model.predict(X)
for hours, marks in zip(X.ravel(), y_pred):
print(hours, "hours ->", round(marks, 1), "marks")
print("Predicted marks for 6 hours:", round(model.predict([[6]])[0], 1))Slope: 10.0
Intercept: 0.0
1 hours -> 10.0 marks
2 hours -> 20.0 marks
3 hours -> 30.0 marks
4 hours -> 40.0 marks
5 hours -> 50.0 marks
Predicted marks for 6 hours: 60.04.2.2Data storytellingOften examined
Data storytelling uses visuals to communicate insights from data. It combines charts, graphs and narrative (a story in words) to explain findings. A good data story engages the audience and makes data relatable.
- It helps in data-driven decisions by highlighting the key points.
- Clear storytelling simplifies complex data for better understanding.
- It shows the impact of data on real-world issues.
- Effective data stories make information memorable and actionable.
- They give context and meaning to raw data.
- It bridges the gap between data and decision-making, turning data into a compelling narrative.
Case study: improving school attendance
Context: a school wants to improve student attendance.
| Data item | Value |
|---|---|
| Average attendance rate | 85% |
| Highest attendance rate | 9th grade (90%) |
| Lowest attendance rate | 12th grade (78%) |
| Average absences per student | 5 days |
Story: Meet Jameel, a 12th-grade student who represents the school's attendance challenge. Jameel misses an average of 5 days of school, which puts him at risk of falling behind. But the 9th-grade students show that it is possible to do better, with an impressive 90% attendance rate. If we identify the factors behind their success and apply them to 12th-grade students, we could help Jameel and his fellows stay on track. Let us work together to make attendance a priority.
Key elements of the story
- Relatable character: Jameel.
- Contextual data: attendance rates and absences.
- Insight: the success of the 9th grade.
- Call to action: apply these insights to 12th-grade students.
This simple story uses data to paint a picture, create empathy and inspire action. It shows how storytelling makes complex information more engaging and memorable.
GlossaryReading and critiquing data stories
Reading and critiquing (judging) data stories improves understanding. To judge a data story, look for clarity and accuracy in the published visuals. The book's glossary and Activity 2 give five criteria.
- Clarity of purpose
- A good data story has a clear goal or message. The first step is to understand the objective.
- Data accuracy and source credibility
- The data must be accurate, and its sources must be reliable and credible.
- Relevance
- The data and the narrative must be directly connected to the main topic or issue.
- Insight
- The deeper understanding the story gives beyond plain facts: patterns, trends or conclusions that help the audience learn something new or decide better.
- Persuasion
- How well the story influences or convinces the audience to act or to consider a point of view.
Common misleading or biased elements
- Truncated axis: a bar chart whose y-axis starts at 70 instead of 0 makes a small difference look huge.
- Cherry-picking: showing only the months or groups that support the message.
- Small or unrepresentative sample: for example asking only 20 students of one school and claiming it is true for the whole country.
- Missing source or date: the reader cannot check the data.
- Correlation shown as causation: two things rising together does not prove one causes the other.
- Loaded words and colours: red for one side only, or emotional headlines not backed by numbers.
How to reduce bias and improve a story
- Check the source and collection method; prefer official or peer-reviewed data.
- Use a representative and large enough sample, and report its size.
- Start numerical axes at zero for bar charts and label every axis with units.
- Show the full data (all groups and time periods) and mention limitations.
- Get feedback from other people (peer review) and improve the visuals and narrative.
4.2.3Formulating questions and data evaluation
Formulating questions guides data exploration and analysis. After asking the questions, we identify the relevant datasets that can answer them, and evaluate how well the data addresses the questions. Evaluation also compares new data with previous findings to see whether they agree.
- Questions focus the analysis on specific insights and trends.
- Questions are refined after evaluation to ensure data quality.
- Good-quality questions give accurate results; effective question formulation drives meaningful analysis.
- Data evaluation helps in understanding and interpreting the findings.
Example: school breakfast programme and attendance
Topic: analysing the impact of school breakfast programmes on student attendance.
| Stage | Book example |
|---|---|
| Formulating questions | 1. Does taking part in a school breakfast programme improve attendance? 2. Which grade levels benefit most? 3. Do students from low-income families improve more than their peers? |
| Identifying relevant datasets | 1. Student attendance records. 2. Breakfast programme participation data. 3. Demographic data (grade level, family income, etc.) |
| Evaluating data quality | 1. Check for missing or inconsistent data. 2. Make sure attendance records are accurate and up to date. 3. Verify that participation data matches student records. |
This example shows how formulating questions guides data exploration and analysis, leading to meaningful insights and informed decision-making.
4.2.4Descriptive statistics techniquesOften examined
Descriptive statistics summarise and describe a dataset with a few numbers and charts. They are frequently used to get true insight and make informed decisions in machine learning. They fall into three groups.
Measures of central tendency
- Mean
- The average value of the dataset: add all values and divide by how many there are.
- Median
- The middle value when the data is arranged in order. For an even number of values it is the mean of the two middle values.
- Mode
- The most frequent value in the data.
Here is the mean, the values and the number of values.
Measures of dispersion (spread)
- Range
- The difference between the highest and lowest values.
- Variance
- The average of the squared differences from the mean.
- Standard deviation
- Measures how spread out the values are around the mean. It is the square root of the variance and has the same unit as the data.
Frequency distribution
- Percentile
- A value below which a certain percentage of the data falls. For example, the 90th percentile of marks is the mark below which 90% of students scored.
- Histogram
- A bar chart that shows the frequency distribution of numerical data: how many values fall in each class (range of values). Bars touch each other.
- Mean: add the 10 values (sum 650) and divide by 10.
- Median: the data is already in order; with 10 values the middle two are the 5th and 6th (60 and 65).
- Mode: 60 occurs twice, every other value once.
- Range: highest minus lowest.
- Variance: square each distance from 65 and average them. Squares: 400, 225, 100, 25, 25, 0, 25, 100, 225, 625 (sum 1750).
- Standard deviation: square root of the variance.
# Descriptive statistics of the marks of 10 students
import statistics as st
marks = [45, 50, 55, 60, 60, 65, 70, 75, 80, 90]
print("Mean =", st.mean(marks))
print("Median =", st.median(marks))
print("Mode =", st.mode(marks))
print("Range =", max(marks) - min(marks))
print("Variance =", st.pvariance(marks))
print("Std dev =", round(st.pstdev(marks), 2))Mean = 65
Median = 62.5
Mode = 60
Range = 45
Variance = 175
Std dev = 13.234.3Hypothesis formulation and hypothesis testingOften examined
Hypothesis formulation is the process of making an educated guess or assumption about a relationship between variables, based on existing data or prior knowledge. The hypothesis is a starting point for investigating how certain factors might influence an outcome. It gives a framework for testing whether the relationship really exists in the data.
Example
Hypothesis: "Increased study hours lead to better exam scores for students." This hypothesis proposes a cause-and-effect relationship between study hours (the independent variable, the cause we change) and exam scores (the dependent variable, the effect we measure).
- Cause-and-effect relationship (causality)
- The connection between two events or factors where one event (the cause) directly influences or leads to another (the effect).
- Independent variable
- The factor that is changed or chosen, the possible cause (study hours).
- Dependent variable
- The factor that is measured, the possible effect (exam score).
Once a hypothesis is formulated, hypothesis testing is the statistical process of deciding whether the data supports or refutes it. It is a critical tool to validate assumptions, model performance and patterns in data. It uses two key hypotheses, the null hypothesis and the alternative hypothesis, and statistical tools such as p-values and significance tests to decide whether to reject the null hypothesis. It tells us whether a result is statistically significant or merely due to chance.
Fig. 4.12 shows hypothesis formulation as a cycle (literature review, theoretical framework, problem statement, hypothesis) and hypothesis testing as a bell-shaped curve with a "fail to reject" region in the middle and "reject" regions beyond the critical values on both sides (drawn in section 4.3.3).
4.3.1Null and alternative hypothesesOften examined
- Null hypothesis ()
- States that there is no effect or relationship between the variables. It assumes that any observed differences are due to random chance.
- Alternative hypothesis ()
- Suggests that there is a significant effect or relationship between the variables.
The null hypothesis is the default assumption that has to be challenged. The alternative hypothesis is what the researchers want to prove. Testing aims to confirm or reject the null hypothesis, and the results decide which hypothesis is supported. Clear definitions of both are essential for accurate testing; they give the framework for analysing data and drawing conclusions.
| Point | Null hypothesis | Alternative hypothesis |
|---|---|---|
| Statement | No effect, no difference, no relationship | There is an effect, difference or relationship |
| Cause of any difference | Random chance | A real factor |
| Role | Default assumption, the one that is tested | What the researcher wants to prove |
| After the test | Rejected or not rejected | Supported when is rejected |
| Coffee example | Coffee has no effect on cognitive function | Coffee improves cognitive function |
Book example: coffee and cognitive function
- Question: Does drinking coffee improve cognitive function (thinking ability) in students?
- **:** Drinking coffee has no effect on cognitive function in students (any observed difference is due to random chance).
- **:** Drinking coffee improves cognitive function in students (a significant effect exists).
- Testing: researchers collect data on students' cognitive function with and without coffee.
- Result: if the data shows a significant improvement with coffee, is rejected and is supported.
- Conclusion: drinking coffee has a positive effect on cognitive function in students.
4.3.2P-valuesOften examined
A p-value measures how likely the results are due to chance. More exactly, it is the probability of getting a result at least as extreme as the one observed if the null hypothesis were true.
- A low p-value (such as 0.02) means strong evidence against the null hypothesis: the result is unlikely to be luck.
- A high p-value (such as 0.5) means weak evidence: the result could easily be random.
- Understanding p-values helps us interpret test results and makes sure conclusions are based on reliable evidence.
Book examples
Coin: if we toss a coin 10 times and get 7 heads and 3 tails, is the coin unfair, or did this happen by chance? The p-value answers this. The program below finds the probability of 7 or more heads from a fair coin.
# Probability of getting 7 or more heads in 10 tosses of a fair coin
from math import comb
n = 10 # number of tosses
heads = 7 # heads we observed
ways = sum(comb(n, k) for k in range(heads, n + 1))
p_value = ways / 2 ** n # each sequence has probability 1/1024
print("Ways to get 7 or more heads:", ways)
print("P-value =", round(p_value, 3))
if p_value < 0.05:
print("Reject H0: the coin looks unfair")
else:
print("Fail to reject H0: the result can happen by chance")Ways to get 7 or more heads: 176
P-value = 0.172
Fail to reject H0: the result can happen by chanceA p-value of 0.172 is much larger than 0.05, so 7 heads is quite normal for a fair coin. We fail to reject H_0 (the coin is fair).
Fertilizer: plants are divided into two groups; one gets a new fertilizer, the other does not. After a month the fertilized plants are taller. Did the fertilizer really make a difference, or did the plants grow taller by chance? If the p-value is small (like 0.02), taller growth by chance is very unlikely, so the fertilizer probably helped. If the p-value is large (like 0.5), the difference was probably random and the fertilizer might have had no real effect.
4.3.3Significance testingOften examined
Significance testing is a statistical method used to decide whether a result is due to chance or is statistically significant. Statistically significant means the result is likely due to some real effect or factor. The test compares the test statistic with a critical value. Setting a significance level (\alpha) decides the threshold of importance. Significance testing helps in data-driven decisions and is crucial for validating research findings.
Book example: exercise and blood pressure
- Research question: Can exercising for six weeks help lower blood pressure?
- **H_0: Exercise does not affect blood pressure. H_1:** Exercise lowers blood pressure.
- Data: people who exercised for six weeks had a reduction in blood pressure of 8 mmHg.
- Significance test: is this result real or a coincidence? A statistical formula gives p-value = 0.005, that is only a 0.5% chance of getting this result by chance.
- Decision: 0.005 is smaller than \alpha=0.05, so we reject H_0 and accept H_1: exercising for six weeks likely lowers blood pressure.
4.3.4Hypothesis testing and its termsOften examined
Hypothesis testing evaluates assumptions using statistical methods. It uses a set of procedures and terms. The book explains them with one example.
Question: Does drinking coffee improve productivity? H_0: coffee has no effect on productivity. H_1: coffee improves productivity.
| Term | Meaning | Coffee example |
|---|---|---|
| Test statistic | A number that measures how much the data deviates from H_0 | Measure productivity of people who drink coffee and those who do not, then calculate (for example) a t-statistic |
| Confidence interval | The range in which the true value likely falls | 95% confidence interval (5, 15): we are 95% confident the true productivity increase is between 5 and 15 |
| Type I error | Rejecting H_0 when it is actually true (false alarm) | Concluding coffee improves productivity when it does not |
| Type II error | Failing to reject H_0 when it is actually false (missed effect) | Concluding coffee has no effect when it actually does |
| Power | The ability of a test to detect an effect if one exists | Chance of detecting a real productivity increase; a larger sample increases power |
| Significance level (\alpha) | The threshold for deciding that results are significant | \alpha=0.05: if p-value < 0.05, reject H_0 |
| Sample size | Number of observations; it affects the reliability of results | 1000 people give more reliable results than 10 people |
| H_0 actually true | H_0 actually false | |
|---|---|---|
| Reject H_0 | Type I error (probability \alpha) | Correct decision (power) |
| Fail to reject H_0 | Correct decision | Type II error |
Summary points from the book
- Hypothesis testing evaluates assumptions using statistical methods.
- Test statistic measures deviation from H_0.
- Confidence interval estimates true values.
- Type I and Type II errors occur from incorrect conclusions.
- Power detects real effects.
- Significance level sets thresholds.
- Sample size impacts reliability.
4.3.5Steps of simple hypothesis testingOften examined
Simple hypothesis testing follows a fixed sequence of steps.
- Formulate the null and alternative hypotheses.
- Collect data and perform the analysis.
- Calculate the test statistic from the data.
- Compare the test statistic with the critical value to draw conclusions.
- Determine the p-value to assess significance.
- Decide whether to reject or not reject the null hypothesis.
- Use the results to make data-driven decisions.
- Interpret the findings in the context of the research question.
- Report the results clearly with appropriate visuals.
Hypothesis testing helps us understand basic relationships in data. Visuals help in presenting the results: graphs and charts can show the data distributions, test statistics and p-values.
Why each step matters
| Step | Why it is important |
|---|---|
| Hypotheses | Makes the question precise and testable; decides what counts as evidence |
| Collect and analyse data | Evidence must be reliable, relevant and of sufficient size |
| Test statistic | Turns the data into one number showing how far it is from H_0 |
| Critical value and p-value | Give an objective rule, so the decision is not based on opinion |
| Decision | Rejecting or not rejecting H_0 gives a clear conclusion |
| Interpret and report | Links the numbers back to the real question and lets others check and use the results |
4.3.6Creating dashboards with Python
A dashboard is a visual tool that helps us understand data by displaying it as charts, graphs, tables and key numbers on one screen. We can create dashboards in Python. Dash is a framework developed by the company Plotly for building interactive web dashboards. It combines Plotly (interactive charts) with Dash (the web page layout).
# Step 1: Import necessary libraries
# (in Google Colab first run: !pip install dash plotly)
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
# Step 2: Create sample data (e.g., sales data over months)
data = pd.DataFrame({
"Month": ["January", "February", "March", "April", "May"],
"Sales": [100, 200, 150, 300, 250]
})
# Step 3: Create a simple line plot with Plotly
fig = px.line(data, x="Month", y="Sales", title="Sales Over Time")
# Step 4: Initialize the Dash app
app = dash.Dash()
# Step 5: Create the layout for the dashboard
app.layout = html.Div(children=[
html.H1("Simple Sales Dashboard"), # Title of the dashboard
dcc.Graph(
id="sales-graph",
figure=fig # Display the line plot
)
])
# Step 6: Run the app
if __name__ == "__main__":
app.run(debug=True)- Step 1: import libraries. \texttt{dash} for the app, \texttt{dcc} (Dash core components, such as graphs) and \texttt{html} (headings, divisions), \texttt{plotly.express} as \texttt{px} for charts, and \texttt{pandas} as \texttt{pd} for the data table. In Colab the libraries are first installed with \texttt{!pip install dash plotly}.
- Step 2: sample data. A pandas DataFrame with two columns, Month and Sales.
- Step 3: line plot. \texttt{px.line} draws Sales against Month with the title "Sales Over Time".
- Step 4: initialise the app. \texttt{app = dash.Dash()} creates the dashboard application.
- Step 5: layout. \texttt{html.Div} holds an \texttt{H1} title and a \texttt{dcc.Graph} that shows the figure.
- Step 6: run. \texttt{app.run(debug=True)} starts a local web server; the dashboard opens in the browser (or inside Colab).
GlossaryPredictive models, causal models and uses of machine learning
The book's glossary and ERQ 3 add some ideas that are not explained in the main text. They are collected here.
- Predictive outcomes (predictive model)
- Forecast future events based on existing data patterns. The model answers "what will happen?" without needing to know why.
- Causality (causal model)
- Shows cause-and-effect relationships: does changing X actually change Y? The model answers "why does it happen, and what if we change something?"
- Model interpretation
- Helps us understand how a model makes decisions. It explains why the model gives certain predictions.
| Point | Predictive model | Causal model |
|---|---|---|
| Question answered | What will happen next? | Why does it happen? What happens if we change X? |
| Based on | Patterns and correlations in past data | Cause-and-effect reasoning, experiments, hypothesis testing |
| Example | Predict next month's sales, spam or not spam, tomorrow's temperature | Does a breakfast programme cause higher attendance? Does exercise lower blood pressure? |
| Uses | Forecasting, recommendations, fraud alerts | Policy decisions, medicine, deciding which action to take |
| Limitation | Correlation is not causation; may fail if conditions change; can copy bias in data | Needs careful experiments or controlled data; hard and costly; hidden factors can mislead |
Applications of machine learning
| Field | Use |
|---|---|
| Healthcare | Predicts disease outbreaks and helps diagnose conditions |
| Finance | Detects fraudulent transactions to protect accounts |
| Retail | Personalises shopping experiences for customers |
| Transportation | Optimises delivery routes to save time |
| Agriculture | Monitors crop health for better yields |
| Education | Tailors learning materials to individual needs |
| Entertainment | Recommends movies or songs based on user preferences |
Formula sheet
Key terms
- Data
- A collection of raw facts and figures collected from different sources.
- Machine learning
- A method in which computers learn from existing data to make new decisions or predictions.
- Machine learning model
- A model that learns from data to make decisions and improves as it gets more data.
- Rule-based algorithm
- An algorithm that follows fixed instructions; it does not change unless someone deliberately updates it.
- Structured data
- Data organised in tables with rows and columns, such as databases and spreadsheets.
- Semi-structured data
- Data in a specific format but without a fixed schema, such as XML and JSON files.
- Unstructured data
- Data without a predefined structure, such as text, images, audio, video and emails.
- Nominal data
- Categorical data with no natural order, such as colour or gender.
- Ordinal data
- Categorical data with a natural order, such as small, medium, large.
- Model building
- Creating a mathematical or computational model that represents relationships between variables in data to make predictions or gain insights.
- Feature engineering
- Selecting and transforming the most relevant data features to improve a model's performance.
- Training data
- The main dataset used to teach a model to make predictions or decisions.
- Test data
- A small portion of data kept aside to evaluate a trained model.
- Test-train split
- Dividing data into training data (main portion) and test data (smaller portion), for example 70:30.
- Validation set
- A separate part of the data used during training to check accuracy on unseen data.
- Supervised learning
- Learning from labelled data where the correct output is given for each input; for example linear regression.
- Unsupervised learning
- Learning from unlabelled data by finding patterns or groups on its own; for example K-Means clustering.
- Reinforcement learning
- Learning by interacting with an environment and receiving rewards or penalties; for example Q-Learning.
- Regression algorithm
- Predicts continuous values such as prices.
- Classification algorithm
- Sorts data into categories.
- Clustering algorithm
- Groups similar data points together.
- Neural network
- An algorithm used for complex patterns and large data such as images and text.
- Overfitting
- The model learns the training data too well, including noise, so it performs well on training data but poorly on new data.
- Underfitting
- The model is too simple to capture the pattern, so it performs poorly on both training and new data.
- Model assessment
- Evaluating a model's performance using measures like accuracy, precision and recall.
- Accuracy
- The percentage of total predictions that are correct.
- Precision
- Of the predictions made for a class, the fraction that are actually correct.
- Recall
- Of all the actual positive cases, the fraction the model correctly identifies.
- F1 score
- The harmonic mean of precision and recall; useful for imbalanced data.
- Continuous learning
- The model keeps learning from new data so that it stays accurate over time.
- Predictive outcomes
- Forecasts of future events based on existing data patterns.
- Causality
- A cause-and-effect relationship between two events or factors.
- Model interpretation
- Understanding how a model makes decisions and why it gives certain predictions.
- Data visualization
- The graphical representation of information and data using charts, graphs and maps.
- Dashboard
- A visual tool that displays data as charts, graphs and tables on one screen.
- Dash
- A Python framework by Plotly for building interactive web dashboards.
- Data storytelling
- Using visuals and narrative to communicate insights from data.
- Clarity of purpose
- A data story has a clear goal or message.
- Relevance
- The data and narrative are directly connected to the main topic.
- Insight
- The deeper understanding a data story gives beyond plain facts.
- Persuasion
- How well a data story convinces the audience to act or consider a view.
- Formulating questions
- Asking focused questions that guide data exploration, then identifying and evaluating relevant data.
- Descriptive statistics
- Techniques such as mean, median, mode, range, variance and standard deviation that summarise data.
- Mean
- The average value of a dataset.
- Median
- The middle value when data is ordered.
- Mode
- The most frequent value in the data.
- Range
- The difference between the highest and lowest values.
- Variance
- The average of squared differences from the mean.
- Standard deviation
- A measure of how spread out values are; the square root of the variance.
- Percentile
- A value below which a given percentage of the data falls.
- Histogram
- A chart that displays the frequency distribution of numerical data.
- Hypothesis formulation
- Making an educated guess about a relationship between variables based on existing data or prior knowledge.
- Null hypothesis (H_0)
- States there is no effect or relationship; differences are due to chance.
- Alternative hypothesis (H_1)
- States there is a significant effect or relationship.
- P-value
- Measures how likely the results are due to chance; a low value is strong evidence against H_0.
- Significance testing
- A method to decide whether a result is due to chance or is statistically significant.
- Significance level (\alpha)
- The threshold, usually 0.05, below which a p-value is called significant.
- Test statistic
- A number measuring how much the data deviates from H_0.
- Critical value
- The boundary value of the test statistic beyond which H_0 is rejected.
- Confidence interval
- The range in which the true value likely falls, for example with 95% confidence.
- Type I error
- Rejecting H_0 when it is actually true.
- Type II error
- Failing to reject H_0 when it is actually false.
- Power
- The ability of a test to detect an effect if one exists.
- Sample size
- The number of observations; larger samples give more reliable results.
Multiple choice questionsp. 121–122
- AIt helps to delete all emails
- BIt learns from past emails to identify spam emailsAnswer
- CIt increases the email storage capacity
- DIt marks all the emails to spam
A spam filter is a machine learning model: it learns from the labels (spam or not spam) of past emails and uses the learned keywords to send similar new emails to the spam folder. It does not delete or mark all emails, and it has nothing to do with storage.
- AThe model performs poorly on training data
- BThe model performs well on training data but poorly on new dataAnswer
- CThe model performs equally well on all types of data
- DThe model does not generate results at all
An overfitted model memorises the training data, including its noise, so it scores well on training data but poorly on new, unseen data. Poor performance on training data (A) is underfitting.
- ACollecting raw data
- BTransforming and selecting relevant data featuresAnswer
- CTesting the model's accuracy
- DCalculating the significance of the model
Feature engineering is the process of selecting and transforming the most relevant data features (such as size, colour and ear shape of animals) to improve a model's performance.
- AThe percentage of total correct predictions
- BThe measure of how many positive predictions are correctAnswer
- CThe measure of how well the model identifies all actual positive cases
- DThe percentage of training data used
Precision = TP / (TP + FP): of the predictions made for the positive class, how many are correct. Option A is accuracy and option C is recall.
- AIt reduces the model's accuracy over time
- BIt helps the model improve its performance by adapting to new dataAnswer
- CIt makes the model slower to process data
- DIt simplifies the model's decision-making process
Continuous learning keeps the model learning from new data, so it stays accurate and improves its accuracy over time.
- ABy focusing solely on statistical analysis
- BBy using visuals and narrative to make data relatable and engagingAnswer
- CBy ignoring complex data patterns
- DBy minimizing the use of charts and graphs
Data storytelling combines charts and graphs with a narrative, which makes data relatable, engaging and memorable. It uses more visuals, not fewer.
- AIt proposes that there is a significant effect or relationship between variables
- BIt assumes that observed differences are due to random chanceAnswer
- CIt is the hypothesis that researchers want to disprove
- DIt is a statistical method used to measure variability
The null hypothesis states there is no effect or relationship and assumes any observed difference is due to random chance. Option A describes the alternative hypothesis. Option C is tempting (researchers often hope to reject H_0), but it describes the researcher's aim, not what the null hypothesis states.
- AThe probability that the null hypothesis is true
- BThe probability that the results are due to some random chanceAnswer
- CThe significance level for the test statistics
- DThe confidence interval for the hypothesis
The book defines the p-value as a measure of how likely the results are due to chance. Option A is a common misconception: the p-value is calculated assuming H_0 is true, so it cannot be the probability that H_0 is true. The significance level (\alpha) is chosen before the test.
- ATo replace the need for statistical analysis
- BTo present data in a more understandable manner and enhance communicationAnswer
- CTo make the data collection process easier
- DTo avoid need of a hypothesis formulation
Visuals such as distribution graphs, test statistics and p-value charts help present the results of hypothesis testing clearly. They support the statistics; they do not replace them.
- ASource of data
- BClarity of the visual presentation
- CThe time of day the data was collectedAnswer
- DRelevance to the topic
Credibility depends on the source of the data, its accuracy, clear presentation and relevance. The time of day the data was collected usually has nothing to do with whether the story can be trusted.
- AThe model is underfitting
- BThe data is imbalancedAnswer
- CThe model is overfitting
- DLabels are missing in training data
When one class is very common (for example 98% of cases are negative), a model can get high accuracy by mostly predicting the common class while doing badly on the rare class, so precision and recall are low. This is the sign of imbalanced data.
- ALogistic regression
- BClusteringAnswer
- CDecision trees
- DLinear regression
With no labels, the task is unsupervised learning. Clustering (such as K-Means) groups similar customers together; the book gives customer segmentation as its example. The other three are supervised methods that need labels.
Short response questions (SRQs)p. 122–123
Feature engineering is the process of selecting and transforming the most relevant features (measurable properties) of the data so that a machine learning model performs better. Good features make the pattern easier for the model to learn; irrelevant features confuse it.
Example (image classification): to classify images of dogs, cats and horses, we list the common and distinct features of each animal, such as body size, colour, shape of the eyes, ears, nose and hair (fur). The model keeps data about the possible variations of these features, so that a sitting horse is not confused with a big standing dog.
| Overfitting | Underfitting |
|---|---|
| The model learns the training data too well, including its noise and irrelevant details. | The model is too simple and fails to capture the underlying pattern. |
| Very good on training data, poor on new, unseen data. | Poor on training data and poor on new data. |
| Cause: model too complex or too specific to the training set. | Cause: model too simple or has not learned enough. |
| Example: a student memorises past papers and fails when questions change. | Example: a student studies too little and fails every question. |
Test data is a small portion of the dataset kept aside and not shown to the model during training. After training, the model is run on the test data and its answers are compared with the correct labels.
Its purpose is to check how well the model works on new, unseen data, which is what it will face in real use. It gives a fair measure of accuracy, precision and recall, and it shows problems such as overfitting (high training accuracy but low test accuracy). For example, from 100,000 animal images, 30,000 unseen images can be used as test data.
Model assessment is the evaluation of a trained machine learning model's performance, using measures such as accuracy, precision and recall, on data it has not seen before. It tells us whether the model is good enough to deploy.
- Accuracy: the percentage of all predictions that are correct, \dfrac{\text{correct predictions}}{\text{total predictions}}. If 80 of 100 new images are labelled correctly, accuracy is 80%.
- Precision: of the predictions made for a class, how many are correct, \dfrac{TP}{TP+FP}. (Recall, \dfrac{TP}{TP+FN}, and the F1 score are also used.)
The main goal of data visualization is to represent data graphically (charts, graphs, maps, dashboards) so that trends, patterns and outliers can be seen and understood quickly.
It turns large tables of numbers into pictures the brain reads at a glance, helps the analyst explore the data, and communicates findings clearly to others, including non-technical audiences, so that better decisions can be made. For example, a line chart of monthly sales instantly shows in which month sales dropped.
Data storytelling is the use of visuals (charts and graphs) together with a narrative to communicate insights from data. It usually has a relatable character, context data, an insight and a call to action.
Importance: it makes data relatable, engaging and memorable; it simplifies complex data; it highlights the key points for data-driven decisions; it shows the impact of data on real issues; and it bridges the gap between data and decision-making. Example: the story of Jameel, a 12th-grader with 78% class attendance, compared with 9th-graders at 90%, persuades the school to act.
Continuous learning means the model keeps learning from new data after it is first trained, instead of staying fixed.
- It keeps the model accurate when the real world changes (new trends, new behaviour).
- It improves accuracy over time, because every new example adds to what the model knows.
- It prevents the model from becoming out of date.
Example: a spam filter learns new spam words each time users mark new emails as spam, so it can catch new kinds of spam that did not exist at training time.
A test-train split divides the dataset into two parts: training data (the main, larger portion used to teach the model) and test data (the smaller portion kept aside to evaluate it). A common ratio is 70:30 or 80:20.
Importance: it lets us measure the model on data it has never seen, which gives an honest estimate of real-world performance and exposes overfitting. The ratio must be chosen wisely: too little training data makes the model underfit, and (as the book states) too much training data with too small a test set leads to an overfitted model going unnoticed. Example: 70,000 of 100,000 animal images for training, 30,000 for testing.
The significance level (\alpha) is the threshold, chosen before the test, for deciding whether a result is significant. Usually \alpha=0.05. If the p-value \le\alpha, we reject H_0; otherwise we fail to reject it.
Effect: \alpha is also the risk of a Type I error (rejecting a true H_0). A smaller \alpha (such as 0.01) makes the test stricter: fewer false alarms but a higher chance of missing a real effect (Type II error). A larger \alpha (such as 0.10) does the opposite. Example: a p-value of 0.03 is significant at \alpha=0.05 but not at \alpha=0.01.
Identify bias by asking: Is the source named and credible? Is the sample large and representative? Are any groups or time periods left out (cherry-picking)? Does a chart use a truncated axis or loaded colours? Is a correlation presented as a cause?
Mitigate bias by using data from reliable sources, using a larger and representative sample, showing the complete data with clear labelled axes starting from zero, stating limitations, separating facts from opinion, and getting feedback from others (peer review) before publishing. Example: a claim based on 20 students of one city should be checked against national data.
- Formulate H_0 and H_1.
- Collect data and analyse it.
- Calculate the test statistic.
- Compare it with the critical value and find the p-value.
- Decide to reject or not reject H_0.
- Interpret the findings and report them with visuals.
Importance: the steps make the investigation objective and repeatable. Clear hypotheses make the question testable; the test statistic and p-value give a fixed rule instead of opinion; and interpreting and reporting connect the result to the real question so that data-driven decisions can be made and checked by others.
Standard deviation (\sigma) measures how spread out the values are around the mean. It is the square root of the variance: \sigma=\sqrt{\dfrac{\sum (x-\bar x)^2}{n}}.
A small standard deviation means the values are close to the mean (consistent data); a large one means they are widely spread. It has the same unit as the data, so it is easy to interpret. Example: two classes both average 65 marks, but class A has \sigma=3 (all students similar) and class B has \sigma=20 (very mixed). The mean alone would hide this difference.
Descriptive statistics reduce thousands of values to a few meaningful numbers and charts:
- Central tendency (mean, median, mode) gives the typical value.
- Dispersion (range, variance, standard deviation) shows how spread out the values are.
- Frequency distribution (histograms, percentiles) shows the shape of the data and where most values lie.
Example: for the marks of 50,000 FBISE students, the mean, median, standard deviation and a histogram describe overall performance on one page. Such summaries give quick insight and help make informed decisions, including in machine learning models.
A result is statistically significant when it is unlikely to be due to chance (p-value below \alpha). Significance supports a conclusion by showing the effect is probably real; a non-significant result challenges it by showing the difference could be luck.
Example: people who exercised for six weeks showed an 8 mmHg drop in blood pressure. The p-value was 0.005, below 0.05, so H_0 ("exercise has no effect") is rejected: the conclusion that exercise lowers blood pressure is supported. If the p-value had been 0.4, the claim would be challenged, since such a drop could happen by chance.
Technical analysis produces tables, statistics and model outputs that non-technical people find hard to read. Data visualization turns these into simple charts, maps and dashboards, where a trend or comparison is visible at a glance, so the message is understood without statistics knowledge.
Scenario: a hospital analyst finds, using statistics, that dengue cases rise sharply two weeks after heavy rain. Instead of showing regression output, she shows the hospital board a line chart of rainfall and dengue cases over the year, with the peaks marked. The board immediately sees the pattern and approves extra beds and spraying before the monsoon.
Extended response questions (ERQs)p. 123
Machine learning models
A machine learning model learns from data to make decisions. It adapts and improves over time as it processes more data. Example: a spam filter that learns spam words from emails users have marked as spam.
Rule-based algorithms
A rule-based algorithm follows fixed instructions written by a person (if condition, then action). It does not change unless someone deliberately updates the rules. Example: "if the subject contains the word lottery, move the email to spam".
Differences
| Point | Machine learning | Rule-based |
|---|---|---|
| Source of rules | Learned from data | Written by people |
| Adaptability | Adapts and improves with more data | Fixed until updated by hand |
| Problems | Complex, unexpected, unstructured | Simple, well-defined |
| Data needed | Large datasets | Little data |
| Transparency | Hard to interpret | Easy to explain |
| Resources | High computing power | Low resources, easy to implement |
Advantages of machine learning
- Handles complex and unstructured data such as images and text.
- Learns patterns automatically without explicit programming of every rule.
- Does not need expert knowledge or human intervention for every decision.
- Becomes more accurate as the dataset grows and keeps improving through continuous learning.
Limitations of machine learning
- Performs poorly if data is too little.
- Its decision-making is complex and cannot be easily interpreted.
- Needs significant computational resources.
- A too-complex model can overfit.
- Biased training data gives wrong results.
Advantages of rule-based algorithms
- Do not need large datasets; work with limited data.
- Consistent performance with the same set of rules.
- Need fewer resources and are easy to implement.
Limitations of rule-based algorithms
- Limited flexibility: cannot adapt to new data the rules did not expect.
- Give wrong results for unstructured or ambiguous data.
- Cannot learn from data.
- Many accumulated rules slow the system down.
Conclusion
Use a rule-based algorithm when the rules are clear, data is limited and decisions must be explained (for example calculating income tax). Use machine learning when patterns are complex and plenty of data is available (for example recognising faces or filtering spam).
Meaning
Model building is the process of creating a mathematical or computational model that learns relationships in data so that it can make predictions or decisions. It is done in steps, and the steps are repeated until the model is good enough. Example used throughout: a model that identifies images of dogs, cats and horses.
1. Data collection
Data is collected from various sources: databases, files, sensors, the internet. For our example we gather a large set of animal images (say 100,000), each labelled cat, dog or horse. More and better-quality data lets the model learn better.
2. Data preprocessing and feature engineering
Raw data is usually messy, so it is cleaned to make it suitable for analysis:
- Handling missing data: fill or remove missing values.
- Normalising values: bring numbers to a similar scale, for example pixel values from 0 to 255 to the range 0 to 1.
- Encoding categorical variables: convert labels such as cat, dog and horse into numbers.
- Feature engineering: select and transform the most relevant features, such as size, colour, ear and eye shape.
Then the data is split into training data and test data (for example 70:30), with a validation set used during training.
3. Choosing an algorithm and training
A suitable algorithm is chosen for the problem: classification (our animal example), regression, clustering or another type. The algorithm is trained on the training data. During training it adjusts its parameters to reduce error and improve accuracy. Training may be supervised (labelled data), unsupervised or reinforcement learning.
4. Evaluation
During training, performance is checked on a separate validation set to be sure the model works on unseen data. After optimisation, it is tested on the final test dataset using accuracy, precision, recall and F1 score. For example, if it labels 80 of 100 new images correctly, its accuracy is 80%. Evaluation also detects overfitting (good on training, poor on test) and underfitting (poor on both).
5. Deployment and refinement
If results are satisfactory, the model is deployed for real-world use. If not, we return to earlier steps: collect more data, improve features or choose another algorithm. Every time the model reads data and calculates results, it keeps learning; repeated refinement and evaluation give a model that meets the needs of the application.
Predictive models
A predictive model forecasts future events or unknown values from patterns in existing data. It answers "what will happen?" and does not need to know why.
- Uses: forecasting sales, predicting exam marks from study hours (linear regression), spam detection, weather forecasts, fraud alerts, film and song recommendations.
- Limitations: it relies on correlation, not causation; it can fail when conditions change (for example a pandemic changes buying habits); it can copy bias present in the training data; complex models are hard to interpret.
Causal models
A causal model explains cause-and-effect relationships: whether changing one factor (the cause) actually changes another (the effect). It answers "why does it happen?" and "what will happen if we change X?"
- Uses: deciding policies and actions, for example whether a breakfast programme causes higher attendance, or whether exercise lowers blood pressure; testing medicines; judging the effect of a price change.
- Limitations: needs carefully designed experiments or controlled data and hypothesis testing; can be costly and slow; hidden (confounding) factors can give a false cause; ethical limits on experiments with people.
Comparison
| Point | Predictive model | Causal model |
|---|---|---|
| Question | What will happen? | Why, and what if we change something? |
| Based on | Correlations and patterns in past data | Cause-and-effect reasoning and experiments |
| Goal | Accurate forecasts | Understanding and decision-making |
| Example | Ice-cream sales predict sunburn cases | Hot sun causes both ice-cream sales and sunburn |
| Strength | Works with large observational data, fast | Tells which action will change the outcome |
| Weakness | Correlation is not causation | Harder data and experiments needed |
Conclusion
Both are needed. A predictive model tells a shop that sales will rise next week; a causal model tells it whether a discount will be the reason. In the book's example, "increased study hours lead to better exam scores" is a causal hypothesis, while predicting marks from hours with linear regression is a predictive model.
Role of research questions
Formulating questions guides data exploration and analysis. A good research question decides what data to collect, which variables to measure, which analysis to use and how to judge the answer. Vague questions produce vague results; specific questions give accurate, useful insights.
How good questions improve quality
- Focus: the question points the analysis at specific insights and trends, so time is not wasted on irrelevant data.
- Choosing data: it identifies which datasets are relevant.
- Evaluation: we can check how well the data answers the question and compare new data with previous findings.
- Refinement: questions are refined after evaluation, which improves data quality.
- Testability: a precise question can be turned into null and alternative hypotheses.
Example: school breakfast programme
Topic: the impact of school breakfast programmes on student attendance.
- Questions: Does taking part in a breakfast programme improve attendance? Which grade levels benefit most? Do students from low-income families improve more than their peers?
- Relevant datasets: student attendance records, breakfast programme participation data, demographic data (grade level, family income).
- Evaluating data quality: check for missing or inconsistent data; make sure attendance records are accurate and up to date; verify that participation data matches student records.
- Meaningful insight: because the third question was specific, the analysis compared low-income participants with non-participants. Suppose it found their attendance rose from 80% to 90% while other students changed little. The school then targets the programme at low-income students, which is an informed, data-driven decision.
Conclusion
Effective question formulation drives meaningful analysis: good questions lead to better data, better evaluation and better decisions.
Hypothesis formulation
Hypothesis formulation is making an educated guess about a relationship between variables, based on existing data or prior knowledge. It names an independent variable (the cause) and a dependent variable (the effect) and proposes how they are related. It is the starting point of an investigation.
Null and alternative hypotheses
- **Null hypothesis (H_0):** there is no effect or relationship; any difference is due to random chance. It is the default assumption that must be challenged.
- **Alternative hypothesis (H_1):** there is a significant effect or relationship. It is what the researcher wants to show.
How they guide research and decisions
- They turn a vague idea into a precise, testable statement.
- They decide what data must be collected and what counts as evidence.
- The test aims to reject H_0. If the p-value is below the significance level (\alpha=0.05), H_0 is rejected and H_1 is supported; otherwise we fail to reject H_0.
- The conclusion leads to a decision: adopt, change or reject a policy or product.
Real-world example: exercise and blood pressure
- Question: Can exercising for six weeks lower blood pressure?
- Hypotheses: H_0: exercise does not affect blood pressure. H_1: exercise lowers blood pressure.
- Data: blood pressure of people before and after six weeks of exercise; the average reduction was 8 mmHg.
- Test: a statistical test gives p-value =0.005, only a 0.5% chance of such a drop by luck.
- Decision: 0.005<0.05, so reject H_0 and accept H_1.
- Use: a doctor can confidently advise six weeks of exercise to patients with high blood pressure; a health department can start an exercise campaign.
Conclusion
Hypothesis formulation gives the question; H_0 and H_1 give the two possible answers; testing with data decides between them, so decisions are based on evidence rather than opinion.
A published data story to critique
Suppose a news website publishes: "Online classes destroyed results! Pass rate crashed." It shows a bar chart with two bars, pass rate 78% in 2019 and 72% in 2021, with the y-axis starting at 70%, so the 2021 bar looks one third as tall as the 2019 bar. The data is from "a survey" of 50 students of one college. No source link is given.
Checking clarity
- Purpose is clear (online classes and results), but the message is exaggerated.
- The chart has no axis titles or units, and it does not say which exam or which students.
Checking accuracy and credibility
- Source is not named, so it cannot be checked.
- Sample of 50 students from one college is small and not representative of the country.
- Only two years are shown; 2020 and 2022 are missing (cherry-picking).
Misleading or biased elements
- Truncated y-axis makes a 6-point fall look like a crash.
- Causation claimed from correlation: many other factors changed in 2021 (illness, exam pattern, grading policy).
- Loaded words ("destroyed", "crashed") push the reader's emotions rather than the data.
Suggested improvements
- Name the source (for example the board's official results) and give the sample size.
- Use data from several colleges and all years 2018 to 2023 as a line chart.
- Start the y-axis at 0 and label axes with units.
- Use neutral wording: "Pass rate fell from 78% to 72%".
- Mention other possible causes and limitations; say that the data shows a link, not proof of cause.
- Ask peers to review the story before publishing.
After these changes the story scores well on the five criteria: clarity of purpose, accuracy and source credibility, relevance, insight and fair persuasion.
Meaning of p-value
A p-value measures how likely the observed results are due to chance. It is the probability of getting a result at least as extreme as the observed one if the null hypothesis (H_0) were true.
Role in hypothesis testing
- It measures the strength of evidence against H_0. A low p-value (such as 0.02) is strong evidence against H_0; a high p-value (such as 0.5) is weak evidence.
- It is compared with the significance level \alpha (usually 0.05). If p-value \le\alpha, reject H_0: the result is statistically significant. If p-value >\alpha, fail to reject H_0.
- It makes the decision objective, so conclusions rest on reliable evidence rather than opinion.
Examples
- Fertilizer: fertilized plants grew taller. A p-value of 0.02 means taller growth by chance is very unlikely, so the fertilizer probably helped. A p-value of 0.5 means the difference could easily be random.
- Coin: 7 heads in 10 tosses gives a p-value of about 0.17 for "7 or more heads", well above 0.05, so we cannot call the coin unfair.
- Exercise: an 8 mmHg drop in blood pressure with p-value 0.005 is significant, so exercise likely lowers blood pressure.
Limitations of p-values
- A p-value is not the probability that H_0 is true, and 1-p is not the probability that H_1 is true.
- It does not show the size or importance of an effect: with a huge sample, a tiny, useless effect can be significant.
- The cut-off 0.05 is a convention; 0.049 and 0.051 are almost the same evidence but give opposite decisions.
- It depends on sample size: small samples may miss real effects (Type II error).
- Testing many things and reporting only the significant ones (p-hacking) gives false findings.
- It says nothing about bias or poor data collection.
Conclusion
P-values are a useful tool to judge whether findings are significant, but they must be reported with the effect size, confidence interval, sample size and a clear description of the data.
Introduction
Simple hypothesis testing checks a claim with data in a fixed sequence of steps. Each step has a job, and skipping one can lead to a wrong conclusion. Example throughout: does drinking coffee improve productivity?
| Step | What is done | How it helps an accurate conclusion |
|---|---|---|
| 1. Formulate hypotheses | H_0: coffee has no effect. H_1: coffee improves productivity. | Makes the question precise and testable; fixes what would count as evidence. |
| 2. Collect data and analyse | Measure productivity of a sample of coffee drinkers and non-drinkers. | A large, representative sample gives reliable evidence (sample size affects reliability and power). |
| 3. Calculate the test statistic | Compute, for example, a t-statistic. | Summarises how far the data deviates from H_0 in one number. |
| 4. Compare with the critical value | Is the statistic beyond the critical value? | Gives an objective boundary for rejecting H_0. |
| 5. Determine the p-value | Find the probability of such data if H_0 were true. | Measures the strength of evidence; compared with \alpha=0.05. |
| 6. Decide | Reject H_0 if p \le 0.05, otherwise fail to reject. | Gives a clear, rule-based conclusion and controls Type I error. |
| 7. Make data-driven decisions | For example, provide coffee in the office. | Turns the result into action. |
| 8. Interpret in context | Explain what the result means for productivity, including the confidence interval such as (5, 15). | Avoids over-claiming; considers practical importance and errors. |
| 9. Report with visuals | Charts of distributions, test statistic and p-value. | Lets others understand, check and repeat the study. |
Importance in validating research
Together the steps protect against the two errors: rejecting a true H_0 (Type I) and missing a real effect (Type II). They make research objective, repeatable and transparent, so findings can be trusted and used for decisions.
Why accuracy and relevance matter
A data story is only as credible as its data. Accuracy means the numbers are correct and come from credible sources. Relevance means the data and narrative are directly connected to the main topic. If either fails, the audience loses trust and may make wrong decisions.
Challenges
- Unreliable sources: data from unknown websites or social media may be wrong.
- Errors in data: missing values, duplicates, typing mistakes, outdated records.
- Sampling bias: a small or one-sided sample that does not represent the population.
- Misleading visuals: truncated axes, wrong chart type, 3-D effects that distort size.
- Cherry-picking and irrelevant data: choosing only data that supports the message, or adding impressive but unrelated numbers.
- Confusing correlation with causation.
- Storyteller bias: the writer's opinion shapes the story.
Solutions
- Use official and credible sources and cite them with dates.
- Clean and verify the data: check for missing or inconsistent values; cross-check with a second source.
- Use large, representative samples and state the sample size.
- Choose the right chart, label axes, start bar charts at zero.
- Keep every chart linked to the main question; remove unrelated data.
- State limitations and uncertainty honestly; say "linked to" rather than "caused" unless tested.
- Get peer review and audience feedback before publishing.
Example
A story on school attendance that uses current attendance registers (accurate, relevant), states the average 85%, compares grades 9 (90%) and 12 (78%) on a correctly scaled bar chart, and names the school records as its source is far more credible than one using a rumour or old data.
Role of feedback
Feedback is the response of the audience, teachers or peers to a data story. Constructive criticism points out specific weaknesses and suggests improvements. Using it, the storyteller refines the visuals, narrative and data until the story is clear, accurate, relevant, insightful and persuasive (the critique criteria of Activity 2).
How feedback is used
- Collect feedback through presentations, peer review, short surveys or comments.
- Analyse it: group comments under clarity, accuracy, relevance, insight and persuasion.
- Revise charts, wording and data according to the comments.
- Test again with a new audience and repeat.
Examples of constructive criticism leading to improvement
| Feedback received | Improvement made |
|---|---|
| "I could not understand what the chart shows." | Added a title, axis labels and units, and one sentence stating the main message. |
| "The bars look very different but the numbers are close." | Started the y-axis at zero, removing the exaggeration. |
| "Where did this data come from?" | Added the source, date and sample size under the chart. |
| "Too many charts, I lost the point." | Kept only the three charts that answer the main question. |
| "So what should we do?" | Added a clear call to action, as in the Jameel attendance story. |
| "A pie chart with 12 slices is hard to read." | Replaced it with a sorted bar chart. |
Conclusion
Feedback turns a first draft into an effective data presentation. Stories improved this way are easier to understand, more trustworthy and more likely to lead to action.
Why accuracy and relevance matter
A data story is only as credible as its data. Accuracy means the numbers are correct and come from credible sources. Relevance means the data and narrative are directly connected to the main topic. If either fails, the audience loses trust and may make wrong decisions.
Challenges
- Unreliable sources: data from unknown websites or social media may be wrong.
- Errors in data: missing values, duplicates, typing mistakes, outdated records.
- Sampling bias: a small or one-sided sample that does not represent the population.
- Misleading visuals: truncated axes, wrong chart type, 3-D effects that distort size.
- Cherry-picking and irrelevant data: choosing only data that supports the message, or adding impressive but unrelated numbers.
- Confusing correlation with causation.
- Storyteller bias: the writer's opinion shapes the story.
Solutions
- Use official and credible sources and cite them with dates.
- Clean and verify the data: check for missing or inconsistent values; cross-check with a second source.
- Use large, representative samples and state the sample size.
- Choose the right chart, label axes, start bar charts at zero.
- Keep every chart linked to the main question; remove unrelated data.
- State limitations and uncertainty honestly; say "linked to" rather than "caused" unless tested.
- Get peer review and audience feedback before publishing.
Example
A story on school attendance that uses current attendance registers (accurate, relevant), states the average 85%, compares grades 9 (90%) and 12 (78%) on a correctly scaled bar chart, and names the school records as its source is far more credible than one using a rumour or old data.
Note. This question is printed twice in the book (it repeats Q.9). The same answer applies.
Role of feedback
Feedback is the response of the audience, teachers or peers to a data story. Constructive criticism points out specific weaknesses and suggests improvements. Using it, the storyteller refines the visuals, narrative and data until the story is clear, accurate, relevant, insightful and persuasive (the critique criteria of Activity 2).
How feedback is used
- Collect feedback through presentations, peer review, short surveys or comments.
- Analyse it: group comments under clarity, accuracy, relevance, insight and persuasion.
- Revise charts, wording and data according to the comments.
- Test again with a new audience and repeat.
Examples of constructive criticism leading to improvement
| Feedback received | Improvement made |
|---|---|
| "I could not understand what the chart shows." | Added a title, axis labels and units, and one sentence stating the main message. |
| "The bars look very different but the numbers are close." | Started the y-axis at zero, removing the exaggeration. |
| "Where did this data come from?" | Added the source, date and sample size under the chart. |
| "Too many charts, I lost the point." | Kept only the three charts that answer the main question. |
| "So what should we do?" | Added a clear call to action, as in the Jameel attendance story. |
| "A pie chart with 12 slices is hard to read." | Replaced it with a sorted bar chart. |
Conclusion
Feedback turns a first draft into an effective data presentation. Stories improved this way are easier to understand, more trustworthy and more likely to lead to action.
Note. This question is printed twice in the book (it repeats Q.10). The same answer applies.
Important exam questions (not in the exercise)
Likely FBISE questions on this unit that the book's exercise does not ask directly, fully answered.
Data is a collection of raw facts and figures collected from different sources.
| Structured | Semi-structured | Unstructured |
|---|---|---|
| Organised in rows and columns (tables) | Organised in a specific format but with no fixed schema | No predefined structure |
| Easy to search and count | Partly searchable using tags or keys | Hard to search directly |
| Spreadsheets, databases, CSV files | XML and JSON files | Videos, emails, web pages, images, audio |
Both are types of categorical data (data with discrete values or labels).
- Nominal data has categories with names only and no natural order. Examples: gender (male, female), colour (red, green, blue), city. We cannot say one category is greater than another.
- Ordinal data has categories with a natural order or rank, although the gaps between levels are not fixed numbers. Examples: small, medium, large; low, high; class position 1st, 2nd, 3rd.
So we can sort ordinal data, but sorting nominal data has no meaning.
Reinforcement learning is a type of machine learning in which a model (an agent) learns by interacting with an environment. After each action it receives feedback as a reward (for a good action) or a penalty (for a bad one), and it gradually learns the actions that give the most reward.
Algorithm: Q-Learning. Applications: game playing, where a program learns to win by playing many games, and robotic navigation, where a robot learns to reach a goal without hitting obstacles.
- Accuracy: correct predictions (TP + TN) out of all 100.\text{Accuracy}=\dfrac{40+30}{100}=0.70=70\%
- Precision: correct Cat predictions out of all Cat predictions (40 + 10 = 50).\text{Precision}=\dfrac{40}{40+10}=0.80
- Recall: correct Cat predictions out of all real cats (40 + 20 = 60).\text{Recall}=\dfrac{40}{40+20}=0.67
- F1 score: harmonic mean of precision and recall.F1=2\cdot\dfrac{0.80\times0.667}{0.80+0.667}=0.73
The model is right 70% of the time; when it says Cat it is right 80% of the time, but it finds only two thirds of the real cats.
The F1 score is the harmonic mean of precision and recall: F1=2\cdot\dfrac{\text{Precision}\cdot\text{Recall}}{\text{Precision}+\text{Recall}}. It gives one number (0 to 1) that is high only when both precision and recall are high.
In imbalanced data one class is much larger. If only 20 of 1000 patients have a disease, a model that always says "healthy" is 98% accurate but finds no patient, so its recall and F1 are 0. Accuracy hides the failure; F1 exposes it.
| Type I error | Type II error |
|---|---|
| Rejecting H_0 when it is actually true | Failing to reject H_0 when it is actually false |
| A false alarm: we find an effect that is not there | A miss: we fail to find an effect that is there |
| Its probability equals the significance level \alpha | Reduced by increasing the sample size (more power) |
| Coffee example: concluding coffee improves productivity when it does not | Coffee example: concluding coffee has no effect when it actually improves productivity |
A confidence interval is the range of values in which the true value (for example the true average effect) is likely to fall, together with a confidence level such as 95%. It estimates the true value instead of giving only one number.
Example: in the coffee study, the 95% confidence interval for the average productivity increase is (5, 15). This means we are 95% confident that the true increase lies between 5 and 15 units. Because the interval does not include 0, the data suggests coffee does improve productivity. A narrower interval (from a larger sample) gives a more precise estimate.
The power of a test is its ability to detect an effect if one really exists, that is, the probability of correctly rejecting a false H_0. High power means a low chance of a Type II error.
A larger sample size increases power, because random variation averages out and a real effect stands out more clearly. For example, testing coffee on 1000 people is much more likely to detect a real productivity increase than testing it on 10 people, and gives more reliable results.
A test statistic is a number calculated from the sample data that measures how much the data deviates from the null hypothesis (for example a t-statistic). A critical value is the boundary value, set by the significance level \alpha, that separates the \"reject H_0\" region from the \"fail to reject\" region.
Decision: if the test statistic falls beyond the critical value (in the rejection region), the result is significant and H_0 is rejected. If it lies between the critical values, we fail to reject H_0. For a two-sided test at \alpha=0.05 with a normal distribution, the critical values are \pm1.96.
- Independent variable: the factor that is changed or chosen by the researcher; it is the possible cause.
- Dependent variable: the factor that is measured; it is the possible effect, and its value depends on the independent variable.
Example hypothesis: "Increased study hours lead to better exam scores for students." Here study hours is the independent variable and exam score is the dependent variable. The hypothesis proposes a cause-and-effect relationship between them, which can be checked with hypothesis testing.
- Matplotlib (Python library): draws charts such as line, bar and scatter plots from code; used in the study hours vs marks program.
- Seaborn (Python library): makes attractive statistical charts easily on top of Matplotlib.
- Plotly and Dash (Python): Plotly creates interactive charts; Dash builds them into web dashboards.
- R: a language that is especially good at statistical graphics.
- SQL: not a charting tool itself, but used to get the required data from databases before visualising it.
The right tool depends on the task and the skill level of the user.
A dashboard is a visual tool that displays data on one screen as charts, graphs, tables and key numbers (KPIs), so that the current situation and trends can be understood at a glance and decisions can be made quickly. Example: a school dashboard showing marks and attendance of each class.
In Python, dashboards are made with Dash, a framework developed by Plotly. Plotly creates the interactive charts, Dash creates the web page layout (\texttt{html.Div}, \texttt{html.H1}, \texttt{dcc.Graph}), and \texttt{app.run()} starts the dashboard in a browser.
| Classification | Regression | Clustering |
|---|---|---|
| Sorts data into categories (labels) | Predicts a continuous numerical value | Groups similar data points together |
| Supervised (needs labels) | Supervised (needs labels) | Unsupervised (no labels) |
| Example: cat, dog or horse; spam or not spam | Example: house price, temperature, marks from study hours | Example: customer segmentation with K-Means |
Unstructured data (images, audio, video, text) has no rows and columns, and its patterns are very complex. In a cat image the model must deal with colours, shapes, textures, the position of the cat and the angle of the picture.
Neural networks can learn such complex patterns directly from large amounts of data, without a person listing every rule. They can also be trained on huge datasets (for example millions of social media posts on COVID-19) in parallel using powerful computers and GPUs. Traditional algorithms such as regression suit structured data instead.
- Range: highest minus lowest.8-4=4
- Mean of the 5 values (sum 30).\bar x=\dfrac{30}{5}=6
- Squared differences from the mean: (4-6)^2=4, (8-6)^2=4, (6-6)^2=0, (5-6)^2=1, (7-6)^2=1; their sum is 10.\sum (x-\bar x)^2=10
- Variance is the average of the squared differences.\sigma^2=\dfrac{10}{5}=2
- Standard deviation is the square root of the variance.\sigma=\sqrt{2}=1.41
A percentile is a value below which a given percentage of the data falls. If a student's mark is at the 90th percentile, 90% of students scored below it. Percentiles show a value's position within the whole data (the median is the 50th percentile).
A histogram is a bar chart of the frequency distribution of numerical data: the x-axis is divided into classes (such as 60 to 70 marks) and each bar's height shows how many values fall in that class. It shows the shape of the data, where most values lie, the spread and any outliers.
Both learn from experience, but in different ways (Fig. 4.5):
- Machine learning learns from a large number of samples with labels (this image: dog; this image: cat). It needs thousands of examples and finds numerical patterns in them.
- Human learning uses a few examples, descriptions and diagrams (a dog has long ears and a black nose) and comparisons (a dog next to a cat). Humans can learn a new concept from very few examples and use common sense.
A machine can, however, process far more data, much faster and without getting tired.
A machine learning model can be trained in three common ways. They differ in the kind of data and feedback the model receives.
1. Supervised learning
The model is trained on labelled data: every input comes with the correct output. The model learns the mapping from inputs to outputs and then predicts outputs for new inputs.
- Algorithm: Linear Regression (predicts continuous values); classification algorithms for categories.
- Example: predicting marks from study hours; classifying images as cat, dog or horse; spam filtering from emails labelled spam or not spam.
2. Unsupervised learning
The data is unlabelled. The model tries to find patterns, structure or groups in the data on its own.
- Algorithm: K-Means Clustering, which groups similar data points together.
- Example: customer segmentation: a shop groups customers by buying habits (budget buyers, weekend shoppers, big spenders) without being told the groups.
3. Reinforcement learning
The model (agent) learns by interacting with an environment. It tries actions and receives rewards for good actions and penalties for bad ones, and learns the strategy that maximises its total reward.
- Algorithm: Q-Learning.
- Example: a program learning to play a game by playing it many times; a robot learning to move through a room without hitting obstacles.
Comparison
| Point | Supervised | Unsupervised | Reinforcement |
|---|---|---|---|
| Data | Labelled | Unlabelled | Experience from environment |
| Feedback | Correct answer for each example | None | Reward or penalty |
| Goal | Predict label or value | Find groups or patterns | Maximise reward |
| Algorithm | Linear regression | K-Means | Q-Learning |
The choice depends on the problem and the available data: labels available means supervised; no labels means unsupervised; learning by trial and error means reinforcement learning.
Four outcomes
For a positive class such as Cat: TP (predicted Cat, is a cat), FP (predicted Cat, is not a cat), TN (predicted Not Cat, is not a cat), FN (predicted Not Cat, is a cat).
Measures
- Accuracy =\dfrac{TP+TN}{TP+TN+FP+FN}: the percentage of all predictions that are correct; how often the model is right overall.
- Precision =\dfrac{TP}{TP+FP}: of the predictions made for the class, how many are correct (quality of positive predictions).
- Recall =\dfrac{TP}{TP+FN}: of the actual positive cases, how many the model found (ability to find all relevant instances).
- F1 score =2\cdot\dfrac{\text{Precision}\cdot\text{Recall}}{\text{Precision}+\text{Recall}}: harmonic mean of the two; useful for imbalanced data.
Program
The program compares 10 actual labels with the model's predictions, counts the four outcomes for Cat with an if-elif chain, and applies the formulas.
# Accuracy, precision, recall and F1 score for the class "Cat"
actual = ["Cat", "Cat", "Dog", "Cat", "Horse", "Dog", "Cat", "Horse", "Dog", "Cat"]
predicted = ["Cat", "Dog", "Cat", "Cat", "Horse", "Dog", "Cat", "Cat", "Dog", "Cat"]
tp = fp = fn = tn = 0
for a, p in zip(actual, predicted):
if p == "Cat" and a == "Cat":
tp += 1 # said Cat, really Cat
elif p == "Cat" and a != "Cat":
fp += 1 # said Cat, but not a Cat
elif p != "Cat" and a == "Cat":
fn += 1 # missed a real Cat
else:
tn += 1 # said Not Cat, really Not Cat
correct = sum(1 for a, p in zip(actual, predicted) if a == p)
accuracy = correct / len(actual)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print("TP =", tp, " FP =", fp, " FN =", fn, " TN =", tn)
print("Accuracy =", round(accuracy, 2))
print("Precision =", round(precision, 2))
print("Recall =", round(recall, 2))
print("F1 score =", round(f1, 2))TP = 4 FP = 2 FN = 1 TN = 3
Accuracy = 0.7
Precision = 0.67
Recall = 0.8
F1 score = 0.73Interpretation
Accuracy 0.7 means 7 of 10 images were labelled correctly. Precision 0.67 means 2 of the 6 "Cat" predictions were wrong. Recall 0.8 means the model found 4 of the 5 real cats. F1 of 0.73 summarises both. Because accuracy can mislead on imbalanced data, all four measures are reported together during model assessment.
Program
# Descriptive statistics of the marks of 10 students
import statistics as st
marks = [45, 50, 55, 60, 60, 65, 70, 75, 80, 90]
print("Mean =", st.mean(marks))
print("Median =", st.median(marks))
print("Mode =", st.mode(marks))
print("Range =", max(marks) - min(marks))
print("Variance =", st.pvariance(marks))
print("Std dev =", round(st.pstdev(marks), 2))Mean = 65
Median = 62.5
Mode = 60
Range = 45
Variance = 175
Std dev = 13.23Explanation of each measure
- Mean (average): sum of values divided by their number, \bar x=\dfrac{650}{10}=65. It uses every value but is pulled by extreme values.
- Median: the middle value of the ordered data. With 10 values it is the average of the 5th and 6th values, (60+65)/2=62.5. It is not affected by extreme values.
- Mode: the most frequent value, 60 (it occurs twice). Useful for categorical data too.
- Range: highest minus lowest, 90-45=45. Simple, but depends only on two values.
- Variance: average of squared differences from the mean, \sigma^2=\dfrac{1750}{10}=175. \texttt{pvariance} divides by n, as in the book's definition.
- Standard deviation: square root of the variance, \sqrt{175}=13.23 marks. It shows that marks typically lie about 13 marks from the mean.
Notes on the code
- \texttt{import statistics as st} loads Python's built-in statistics module.
- \texttt{max} and \texttt{min} give the highest and lowest values for the range.
- \texttt{round(..., 2)} keeps two decimal places.
- \texttt{st.variance} and \texttt{st.stdev} (sample versions) divide by n-1 and would give 194.44 and 13.94; the population versions match the definitions in this unit.
Together, central tendency (mean, median, mode) and dispersion (range, variance, standard deviation) summarise the whole class in six numbers.
Code
# Import numpy library and give it a short name 'np'
# We use numpy to create and manage arrays (tables of numbers)
import numpy as np
# Import the 'pyplot' part of matplotlib and give it a short name 'plt'
# We use 'pyplot' to make graphs like scatter plots and lines
import matplotlib.pyplot as plt
# Import the LinearRegression class from sklearn's linear_model module
# We use it to create a machine learning model that can draw a straight line through points
from sklearn.linear_model import LinearRegression
# Step 1: Prepare the data (study hours and marks)
X = np.array([[1], [2], [3], [4], [5]]) # Input: hours studied
y = np.array([10, 20, 30, 40, 50]) # Output: marks obtained
# Step 2: Create and train the Linear Regression model
model = LinearRegression()
model.fit(X, y)
# Step 3: Predict the marks based on study hours
y_pred = model.predict(X)
# Step 4: Plot the actual points and the prediction line
plt.scatter(X, y, color='blue') # Plot real data points in blue
plt.plot(X, y_pred, color='red') # Plot the prediction line in red
plt.title('Study Hours vs Marks') # Title of the graph
plt.xlabel('Hours Studied') # X-axis label
plt.ylabel('Marks Obtained') # Y-axis label
plt.show() # Show the final graphExplanation
- Libraries: NumPy (\texttt{np}) creates arrays; Matplotlib's pyplot (\texttt{plt}) draws graphs; \texttt{LinearRegression} from scikit-learn is a machine learning model that fits a straight line through points.
- Step 1, data: \texttt{X} holds hours studied (1 to 5) as a column (2-D array, as scikit-learn needs); \texttt{y} holds marks (10 to 50).
- Step 2, training: \texttt{model = LinearRegression()} creates the model and \texttt{model.fit(X, y)} trains it. This is supervised learning because each input has its correct output.
- Step 3, prediction: \texttt{model.predict(X)} returns predicted marks for each input.
- Step 4, plotting: \texttt{scatter} plots actual points (blue), \texttt{plot} draws the prediction line (red), \texttt{title}, \texttt{xlabel} and \texttt{ylabel} label the graph, \texttt{show} displays it.
Output
A graph titled "Study Hours vs Marks" with Hours Studied (1 to 5) on the x-axis and Marks Obtained (10 to 50) on the y-axis. The five points lie on a straight rising line: every extra hour adds 10 marks.
Printing the model's learned values confirms this:
# Train a Linear Regression model on study hours and marks, then print its predictions
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]]) # input: hours studied
y = np.array([10, 20, 30, 40, 50]) # output: marks obtained
model = LinearRegression()
model.fit(X, y) # the model learns the pattern from the data
print("Slope:", round(model.coef_[0], 2))
print("Intercept:", round(model.intercept_, 2))
y_pred = model.predict(X)
for hours, marks in zip(X.ravel(), y_pred):
print(hours, "hours ->", round(marks, 1), "marks")
print("Predicted marks for 6 hours:", round(model.predict([[6]])[0], 1))Slope: 10.0
Intercept: 0.0
1 hours -> 10.0 marks
2 hours -> 20.0 marks
3 hours -> 30.0 marks
4 hours -> 40.0 marks
5 hours -> 50.0 marks
Predicted marks for 6 hours: 60.0The model has learned marks =10\times hours, so it predicts 60 marks for 6 hours. This shows how machine learning and visualization work together: the model finds the pattern and the graph shows it.
Dashboard
A dashboard is a visual tool that shows data as charts, graphs and tables on one screen, so that users can monitor information and spot trends quickly. Dash is a Python framework developed by Plotly for building interactive web dashboards; Plotly makes the interactive charts.
Code
# Step 1: Import necessary libraries
# (in Google Colab first run: !pip install dash plotly)
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
# Step 2: Create sample data (e.g., sales data over months)
data = pd.DataFrame({
"Month": ["January", "February", "March", "April", "May"],
"Sales": [100, 200, 150, 300, 250]
})
# Step 3: Create a simple line plot with Plotly
fig = px.line(data, x="Month", y="Sales", title="Sales Over Time")
# Step 4: Initialize the Dash app
app = dash.Dash()
# Step 5: Create the layout for the dashboard
app.layout = html.Div(children=[
html.H1("Simple Sales Dashboard"), # Title of the dashboard
dcc.Graph(
id="sales-graph",
figure=fig # Display the line plot
)
])
# Step 6: Run the app
if __name__ == "__main__":
app.run(debug=True)Explanation of the steps
- Step 1: import \texttt{dash}, the components \texttt{dcc} and \texttt{html}, \texttt{plotly.express} as \texttt{px} and \texttt{pandas} as \texttt{pd}. In Colab, install them first with \texttt{!pip install dash plotly}.
- Step 2: create sample data in a pandas DataFrame: months January to May and sales 100, 200, 150, 300, 250.
- Step 3: \texttt{px.line} creates a line chart of Sales against Month titled "Sales Over Time".
- Step 4: \texttt{dash.Dash()} initialises the app.
- Step 5: \texttt{app.layout} is an \texttt{html.Div} containing an \texttt{H1} heading "Simple Sales Dashboard" and a \texttt{dcc.Graph} that displays the chart.
- Step 6: \texttt{app.run(debug=True)} starts a web server; the dashboard appears in the browser. The \texttt{if \_\_name\_\_ == "\_\_main\_\_"} check runs the app only when the file is run directly.
Output
A web page headed "Simple Sales Dashboard" with an interactive line chart: sales rise from 100 in January to 200 in February, dip to 150 in March, peak at 300 in April and fall to 250 in May. Hovering shows exact values.
Example
Question: Does drinking coffee improve productivity? H_0: coffee has no effect on productivity. H_1: coffee improves productivity.
Terms
- Test statistic: a number that measures how much the data deviates from H_0. We measure productivity of people who drink coffee and those who do not, and calculate a statistic such as the t-statistic. The larger it is, the stronger the evidence against H_0.
- Confidence interval: the range where the true value likely falls. A 95% confidence interval of (5, 15) for the productivity increase means we are 95% confident the true increase is between 5 and 15.
- Type I error: rejecting H_0 when it is actually true, that is concluding coffee improves productivity when it does not.
- Type II error: failing to reject H_0 when it is actually false, that is concluding coffee has no effect when it actually does.
- Power: the ability to detect a real productivity increase if coffee really improves it. A larger sample increases power.
- **Significance level (\alpha):** the threshold for significance, set at 0.05. If p-value <0.05, reject H_0. It is also the probability of a Type I error we accept.
- Sample size: the number of people studied. 1000 people give more reliable results than 10 people.
| Decision | H_0 true | H_0 false |
|---|---|---|
| Reject H_0 | Type I error | Correct (power) |
| Fail to reject H_0 | Correct | Type II error |
Summary
The test statistic measures deviation from H_0; the confidence interval estimates the true value; Type I and II errors come from wrong conclusions; power detects real effects; the significance level sets the threshold; and sample size affects reliability. Understanding these terms leads to accurate hypothesis tests and valid conclusions.
Data is a collection of raw facts and figures collected from different sources. The type of data decides how it is stored, visualised and which algorithm learns from it.
| Type | Description | Examples |
|---|---|---|
| Numerical | Quantitative values that can be measured or counted | Marks, salary, age |
| Categorical | Discrete values or labels; nominal (no order) or ordinal (ordered) | Nominal: gender, colour. Ordinal: small, medium, large |
| Boolean | Only two values, 0 or 1 | True/False, Yes/No |
| Text | A sequence of characters | Reviews, feedback, descriptions |
| Time series | Values recorded over a long period in time order | Stock prices, weather data |
| Image | Pixel values | X-rays, ultrasound, photographs |
| Audio | Sound waves | Speech, music |
| Structured | Rows and columns (tables) | Spreadsheets, databases |
| Semi-structured | Specific format but no fixed schema | XML, JSON files |
| Unstructured | No predefined structure | Videos, emails, web pages |
Why the type matters
- Visualization: numerical data suits histograms and scatter plots; categorical data suits bar and donut charts; time series suits line charts.
- Algorithms: structured data suits traditional algorithms like regression and classification; unstructured data (images, text, audio) needs advanced algorithms such as neural networks.
- Preprocessing: categorical data must be encoded as numbers, numerical data may need normalising, and text must be broken into words before a model can learn from it.
FBISE 2026 questions
Questions from the FBISE HSSC-II 2026 (1st Annual) papers that belong to this unit, answered the way an examiner expects.
- ANull Hypothesis (H_0)Answer
- BCause-and-effect Hypothesis
- CAlternative Hypothesis (H_1)
- DResearch Hypothesis
The null hypothesis (H_0) states that there is no effect or relationship between the variables and that any observed difference is due to random chance. The alternative hypothesis (H_1) claims an effect exists.
- ASelf-Learning
- BReinforcement Learning
- CUnsupervised Learning
- DSupervised LearningAnswer
In supervised learning the model is trained on labelled data, where the correct output is given for each input. Unsupervised learning uses unlabelled data, and reinforcement learning uses rewards and penalties.
One mark for each advantage:
- Handles complex and unstructured data: it can work with images, audio, text and large datasets that are too complex for fixed rules.
- Learns patterns automatically: it learns from data without explicit programming of every rule and does not need expert knowledge or human intervention for each decision.
- Improves with more data: it adapts to new data and becomes more accurate over time (continuous learning); for example a spam filter learns new spam words as users mark emails.
A p-value measures how likely the observed results are due to chance, assuming the null hypothesis H_0 is true.
- Evidence: a low p-value (such as 0.02) is strong evidence against H_0; a high p-value (such as 0.5) is weak evidence and the result may be random.
- Decision: it is compared with the significance level \alpha=0.05. If p-value \le 0.05, H_0 is rejected and the result is statistically significant; otherwise we fail to reject H_0.
- Example: plants given a new fertilizer grew taller. A p-value of 0.02 shows the extra growth is very unlikely to be chance, so the fertilizer probably works.
A test-train split divides the dataset into two parts: training data, the main (larger) portion used to teach the model, and test data, the smaller portion kept aside and not shown during training, used to evaluate the model on unseen data.
A common ratio is 70:30 (or 80:20). For example, from 100,000 labelled images of cats, dogs and horses, 70,000 are used for training and 30,000 for testing. The ratio must be chosen wisely: with too little training data the model underfits, and (as the book states) with too much training data it overfits. The split gives an honest measure of real-world accuracy.
Feature engineering is selecting and transforming the most relevant data features to improve a model's performance. It is important because:
- Improves accuracy: relevant features (size, colour, ear and eye shape of animals) make the pattern easy to learn, so predictions are more correct; a sitting horse is not confused with a big standing dog.
- Removes noise and reduces overfitting: dropping irrelevant features stops the model learning useless details.
- Makes training faster and data usable: fewer, cleaner features need less computation, and transforming data (normalising values, encoding categories as numbers) puts it into a form the algorithm can use.
They are measures of central tendency, which describe the typical value of a dataset. Example data: 2, 3, 3, 5, 7.
- Mean: the average value: the sum of all values divided by their number, \bar x=\dfrac{\sum x}{n}=\dfrac{20}{5}=4.
- Median: the middle value when the data is arranged in order. Here the 3rd of 5 values is 3. (For an even number of values, take the average of the two middle values.)
- Mode: the most frequent value in the data. Here 3 occurs twice, so the mode is 3.
Process of hypothesis formulation (2 marks)
Hypothesis formulation is making an educated guess or assumption about a relationship between variables, based on existing data or prior knowledge. It is the starting point for investigating how certain factors might influence an outcome.
- Identify the research problem or question from observation or previous studies (literature review).
- Identify the independent variable (possible cause) and the dependent variable (effect).
- State the expected relationship as a clear, testable statement, for example "Increased study hours lead to better exam scores." This proposes a cause-and-effect relationship.
- Write it as a pair: null hypothesis H_0 and alternative hypothesis H_1, ready for hypothesis testing with data.
Role of null and alternative hypotheses (3 marks)
- **Null hypothesis (H_0):** states there is no effect or relationship; any difference is due to random chance. It is the default assumption that is tested and challenged.
- **Alternative hypothesis (H_1):** states there is a significant effect or relationship. It is what the researcher wants to show.
- Role: they make the question testable and define what counts as evidence. Data is collected and a p-value is found. If p-value <\alpha (0.05), H_0 is rejected and H_1 is supported; otherwise we fail to reject H_0.
Example
- Question: Does drinking coffee improve cognitive function in students?
- H_0: drinking coffee has no effect on cognitive function. H_1: drinking coffee improves cognitive function.
- Researchers compare students' cognitive function with and without coffee.
- If the data shows a significant improvement, H_0 is rejected and H_1 supported: coffee has a positive effect on cognitive function.
- AStrong evidence against H_0Answer
- BWeak evidence against H_0
- CResults due to chance
- DNull hypothesis is always accepted
A low p-value means the result is unlikely to be due to chance, which is strong evidence against the null hypothesis H_0. A high p-value gives weak evidence.
- AFixed instructions only
- BManual data organizing
- CLearn from data to decideAnswer
- DStore data in databases
Machine learning is a method in which computers learn from existing data to make new decisions. Fixed instructions only (A) describes a rule-based algorithm.
| Supervised learning | Unsupervised learning |
|---|---|
| Model is trained on labelled data: the correct output is given for each input. | Data is unlabelled: no correct outputs are given. |
| Learns to predict the label or value for new inputs. | Finds hidden patterns or groups on its own. |
| Used for classification and regression. | Used for clustering. |
| Example: Linear Regression to predict prices or temperatures; classifying emails as spam. | Example: K-Means Clustering for customer segmentation. |
| Null hypothesis H_0 | Alternative hypothesis H_1 |
|---|---|
| States there is no effect or relationship between the variables. | States there is a significant effect or relationship. |
| Assumes observed differences are due to random chance. | Assumes differences are due to a real factor. |
| Default assumption that is tested; it is rejected or not rejected. | What the researcher wants to prove; supported when H_0 is rejected. |
| Example: drinking coffee has no effect on cognitive function. | Example: drinking coffee improves cognitive function. |
Overfitting (1.5): the model learns the training data too well, including its noise and irrelevant details. It performs very well on training data but poorly on new, unseen data, because it has become too specific to the training set. Example: a student who memorises past papers word for word fails when questions change.
Underfitting (1.5): the model is too simple and fails to capture the underlying pattern in the data. It performs poorly on both training data and new data, because it has not learned enough. Example: fitting a flat line to data that clearly rises.
Role (1.5): the p-value measures how likely the results are due to chance if H_0 is true. A low p-value is strong evidence against H_0; a high p-value is weak evidence. It is compared with the significance level \alpha=0.05: if p-value \le0.05, reject H_0 (significant result); otherwise fail to reject it.
Examples (1.5): (1) Exercise for six weeks reduced blood pressure by 8 mmHg with p-value 0.005, below 0.05, so H_0 is rejected: exercise likely lowers blood pressure. (2) Fertilized plants grew taller; a p-value of 0.5 would mean the difference could easily be random, so the fertilizer may have had no real effect.
Data storytelling (2): the use of visuals (charts, graphs) combined with a narrative to communicate insights from data. It makes data relatable, engaging and memorable, simplifies complex data, highlights key points and bridges the gap between data and decision-making.
Example (1): a school's average attendance is 85%, with 9th grade at 90% and 12th grade at 78%. The story of Jameel, a 12th-grader who misses 5 days, shown with a bar chart of the grades, persuades the school to apply the 9th grade's successful practices to the 12th grade.
A machine learning model learns from data to make decisions and improves as it gets more data. A rule-based algorithm follows fixed instructions written by people and changes only when the rules are updated.
Advantages of machine learning over rule-based algorithms (2.5)
- Handles complex and unstructured data such as images, audio and text, which cannot be described by simple rules.
- Learns patterns automatically without explicit programming of every rule and without expert intervention for each case.
- Adapts and improves as more data arrives (continuous learning), whereas rule-based systems need new rules for every new situation.
- Example: a spam filter learns new spam words; a fixed rule "subject contains lottery" misses new spam.
Limitations of machine learning compared with rule-based algorithms (2.5)
- Needs large datasets: it performs poorly when data is too little, while rule-based algorithms work with limited data.
- Hard to interpret: its decision-making is complex, while rules are easy to follow and explain.
- Needs significant computing resources, while rule-based systems are cheap and easy to implement.
- Risk of overfitting and bias: a too-complex model overfits, and biased training data gives wrong results; rule-based output is consistent for the same rules.
Exam focus
- Advantages and limitations of machine learning compared with rule-based algorithms. (long)Asked as a 5-mark Section C question (2026 Set D Q.4) and as a short question (Set B Q.2 (i) OR); also book ERQ 1.Go to answer
- Explain hypothesis formulation and the role of the null and alternative hypotheses with an example. (long)2026 Set B Q.4 (2+3); the difference between H_0 and H_1 was also Set D Q.2 (iv) and an MCQ in both sets.Go to answer
- Role of p-values in hypothesis testing, with examples. (short)Appeared in both 2026 sets (Set B Q.2 (iv), Set D Q.2 (vii) OR) plus an MCQ on what a low p-value means.Go to answer
- Overfitting and underfitting; test-train split; feature engineering. (short)Each was a 3-mark 2026 question (Set D Q.2 (vi) OR, Set B Q.2 (vii) OR, Set B Q.2 (xi) OR).Go to answer
- Difference between supervised and unsupervised learning (and reinforcement learning). (short)2026 Set D Q.2 (iii) and Set B MCQ 8 (labelled data).Go to answer
- Accuracy, precision, recall and F1 score: definitions, formulas and a small calculation. (short)Two book exercise MCQs and SRQ 4 test these; a numerical from TP, FP, FN, TN is an easy 3 marks.Go to answer
- Steps of model building in machine learning. (long)Book ERQ 2; the five-step process is the backbone of the machine learning half of the unit.Go to answer
- Mean, median, mode and standard deviation. (short)2026 Set B Q.2 (xiii) OR; book SRQs 12 and 13.Go to answer
- Data storytelling: meaning, importance and an example; critiquing a data story. (short)2026 Set D Q.2 (xiii) OR; four of the book's ERQs are on data stories.Go to answer
- Steps of simple hypothesis testing and terms (Type I and II errors, significance level, power). (long)Book ERQ 8 and SRQs 9 and 11; a likely Section C question.Go to answer