Data and analysis

Class 12 Computer Science, unit 4, book pages 101–125

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.

Fig. 4.1 redrawn: the spam filter sorts incoming mail using what it learned from emails marked as spam.

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.

Table 4.1: Data types used in data science and machine learning
Data typeDescriptionExamples
NumericalQuantitative data used to represent numerical values (numbers you can measure or count).Marks, salary, age
CategoricalData 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
BooleanHas only two possible values, 0 or 1.True/False, Yes/No
Text dataContains a sequence of characters.Description, review, feedback
Time seriesCollected over a long period of time, one value after another in time order.Stock price, weather data
ImageRepresented as pixel values in the image.X-ray, ultrasound, photographs
AudioIn the form of sound waves.Speech, music
StructuredOrganised in the form of rows and columns (tables).Spreadsheet, database
Semi-structuredOrganised in some specific format, but there is no fixed pattern (schema).XML, JSON files
UnstructuredHas 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.

In a rule-based system people write the rules. In machine learning the algorithm finds the rules (the model) from data and answers.
Machine learning versus rule-based algorithms
PointMachine learning modelRule-based algorithm
How it worksLearns patterns from dataFollows fixed rules written by people
Change over timeAdapts and improves as it gets more dataDoes not change unless rules are updated by hand
Problems handledComplex problems, unexpected situations, unstructured dataSimple, well-defined problems where rules are known
Data neededLarge datasets; accuracy depends on dataset sizeWorks with limited data
BehaviourFlexible and dynamic, can learn new thingsConsistent: same input gives same output
Explaining decisionsHard to interpret (complex decision-making)Easy to follow and explain
ResourcesNeeds significant computing powerNeeds fewer resources, easy to implement
ExampleSpam filter that learns spam wordsRule: 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 check versus a filter that learns from labelled data
Rule-based: inbox
Learned   : spam
Output

4.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.

Fig. 4.3 redrawn: the machine learning model building process. If the model is not good enough, we go back, improve and repeat.
Steps of model building
  1. Step 1: Data collection. Collect data from various sources, for example thousands of labelled images of dogs, cats and horses.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
Splitting a dataset. Fig. 4.4 in the book shows the same idea with doughnut charts (80:10:10 and 60:20:20).

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))
Splitting 10 labelled images in the ratio 70:30
Training images: 7
Test images: 3
Output

Machine 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.
Three types of learning
PointSupervisedUnsupervisedReinforcement
DataLabelled (input with correct output)UnlabelledNo fixed dataset; experience from the environment
GoalPredict the label or value for new inputDiscover hidden groups or patternsLearn actions that earn the most reward
FeedbackCorrect answer for every exampleNoneReward or penalty after actions
Example algorithmLinear regression, classificationK-Means clusteringQ-Learning
Example usePredict house prices, classify emailsCustomer segmentationGame 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.
Three models fitted to the same six points
1
2
3
4
5
1
2
3
4
5
6
7
O
The flat line is too simple (underfit). The wiggly curve passes through every training point, noise included (overfit), so it will predict badly between and beyond the points. The straight line follows the real trend (good fit).
PointOverfittingUnderfitting
CauseModel too complex, or learns noiseModel too simple, or trained too little
Training dataVery high accuracyLow accuracy
New (test) dataLow accuracyLow accuracy
AnalogyA student who memorises past papers word for word and fails when the question changesA student who studied too little and fails both easy and hard questions
RemedyMore training data, simpler model, remove irrelevant featuresMore 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.

OutcomeMeaning (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.
Calculating the four measures
A model is tested on 10 animal images. For the class Cat it gives TP = 4, FP = 2, FN = 1 and TN = 3. Find accuracy, precision, recall and F1 score.
  1. Accuracy uses all correct predictions (TP and TN) out of all 10.
  2. Precision looks only at the 6 images the model called Cat.
  3. Recall looks only at the 5 images that really are cats.
  4. 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))
Counting TP, FP, FN, TN and computing the measures
TP = 4  FP = 2  FN = 1  TN = 3
Accuracy  = 0.7
Precision = 0.67
Recall    = 0.8
F1 score  = 0.73
Output

4.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.

Algorithm selection according to data type
PointStructured dataUnstructured data
MeaningOrganised in tables with rows and columnsUnorganised, no specific structure or predefined format
SearchEasily searchable and quantifiableHard to search directly
ExamplesDatabases, spreadsheets, CSV filesText, images, audio and video files, social media posts, emails, sensor readings
Suitable algorithmsTraditional algorithms such as regression and classificationAdvanced 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

ToolWhat it does
SQLA language that helps us get (query) data from databases before we chart it.
Python: Matplotlib and SeabornLibraries that create charts and graphs from code.
Python: Plotly and DashInteractive charts and web dashboards (section 4.3.6).
RA 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)

VisualBest used for
KPI (key performance indicator)One big number showing a target or result, such as 100% or sales this month
TableExact values in rows and columns
Bar chartComparing values of different categories
Line chartChange over time (trends)
Donut chartParts of a whole (shares or percentages)
Tree mapParts of a whole shown as nested rectangles
Bullet chartProgress of one value against a target
Scatter plotRelationship between two numerical variables, and outliers
Geo mapValues by location (city, province, country)
Radial chartComparing 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 graph
Fig. 4.8: Python code for data visualization

How the program works

  1. Import libraries. as for arrays, as for graphs, and the class from .
  2. 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.
  3. 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).
  4. Step 3: predict. gives the marks the model expects for each number of hours.
  5. Step 4: plot. draws the real points in blue, draws the prediction line in red, and , , add labels. displays the graph.
Study Hours vs Marks (Fig. 4.9)
1
2
3
4
5
6
10
20
30
40
50
60
O
Output of the program: the five data points lie exactly on the prediction line, marks = 10 × hours.

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))
Printing the learned line and a new prediction
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.0
Output

4.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 itemValue
Average attendance rate85%
Highest attendance rate9th grade (90%)
Lowest attendance rate12th grade (78%)
Average absences per student5 days
Attendance rate
20
40
60
80
100
O
A simple bar chart for the story: the gap between 9th and 12th grade is the insight.

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

  1. Relatable character: Jameel.
  2. Contextual data: attendance rates and absences.
  3. Insight: the success of the 9th grade.
  4. 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.

StageBook example
Formulating questions1. 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 datasets1. Student attendance records. 2. Breakfast programme participation data. 3. Demographic data (grade level, family income, etc.)
Evaluating data quality1. 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.

Fig. 4.11 redrawn: descriptive statistics techniques.

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.
Summarising the marks of 10 students
Marks: 45, 50, 55, 60, 60, 65, 70, 75, 80, 90. Find the mean, median, mode, range, variance and standard deviation.
  1. Mean: add the 10 values (sum 650) and divide by 10.
  2. Median: the data is already in order; with 10 values the middle two are the 5th and 6th (60 and 65).
  3. Mode: 60 occurs twice, every other value once.
  4. Range: highest minus lowest.
  5. Variance: square each distance from 65 and average them. Squares: 400, 225, 100, 25, 25, 0, 25, 100, 225, 625 (sum 1750).
  6. 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))
The same results with Python's statistics module
Mean     = 65
Median   = 62.5
Mode     = 60
Range    = 45
Variance = 175
Std dev  = 13.23
Output
Histogram of the 10 marks
40
50
60
70
80
90
100
0
1
2
3
4
Classes of width 10 (for example 60 to under 70). Most students scored between 60 and 70; the mean sits there.

4.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.

PointNull hypothesis Alternative hypothesis
StatementNo effect, no difference, no relationshipThere is an effect, difference or relationship
Cause of any differenceRandom chanceA real factor
RoleDefault assumption, the one that is testedWhat the researcher wants to prove
After the testRejected or not rejectedSupported when is rejected
Coffee exampleCoffee has no effect on cognitive functionCoffee improves cognitive function

Book example: coffee and cognitive function

  1. Question: Does drinking coffee improve cognitive function (thinking ability) in students?
  2. **:** Drinking coffee has no effect on cognitive function in students (any observed difference is due to random chance).
  3. **:** Drinking coffee improves cognitive function in students (a significant effect exists).
  4. Testing: researchers collect data on students' cognitive function with and without coffee.
  5. Result: if the data shows a significant improvement with coffee, is rejected and is supported.
  6. 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.
P-value as a tail area (Fig. 4.14)
If H_0 is true, results cluster in the middle. The shaded tail beyond the observed result is the p-value. A result far in the tail gives a small p-value.

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")
P-value for 7 heads in 10 tosses (one-sided)
Ways to get 7 or more heads: 176
P-value = 0.172
Fail to reject H0: the result can happen by chance
Output

A 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.

Rejection regions for a two-sided test at α = 0.05
Figs. 4.12 and 4.15: the critical values cut off the rejection regions. A test statistic beyond a critical value is significant; one in the middle is not.

Book example: exercise and blood pressure

  1. Research question: Can exercising for six weeks help lower blood pressure?
  2. **H_0: Exercise does not affect blood pressure. H_1:** Exercise lowers blood pressure.
  3. Data: people who exercised for six weeks had a reduction in blood pressure of 8 mmHg.
  4. 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.
  5. 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.
\text{p-value}\le\alpha\ \Rightarrow\ \text{reject } H_0\ (\text{significant}),\qquad \text{p-value}>\alpha\ \Rightarrow\ \text{fail to reject } H_0

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.

Terms of hypothesis testing
TermMeaningCoffee example
Test statisticA number that measures how much the data deviates from H_0Measure productivity of people who drink coffee and those who do not, then calculate (for example) a t-statistic
Confidence intervalThe range in which the true value likely falls95% confidence interval (5, 15): we are 95% confident the true productivity increase is between 5 and 15
Type I errorRejecting H_0 when it is actually true (false alarm)Concluding coffee improves productivity when it does not
Type II errorFailing to reject H_0 when it is actually false (missed effect)Concluding coffee has no effect when it actually does
PowerThe ability of a test to detect an effect if one existsChance 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 sizeNumber of observations; it affects the reliability of results1000 people give more reliable results than 10 people
The four possible outcomes of a test
H_0 actually trueH_0 actually false
Reject H_0Type I error (probability \alpha)Correct decision (power)
Fail to reject H_0Correct decisionType 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.

  1. Formulate the null and alternative hypotheses.
  2. Collect data and perform the analysis.
  3. Calculate the test statistic from the data.
  4. Compare the test statistic with the critical value to draw conclusions.
  5. Determine the p-value to assess significance.
  6. Decide whether to reject or not reject the null hypothesis.
  7. Use the results to make data-driven decisions.
  8. Interpret the findings in the context of the research question.
  9. 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

StepWhy it is important
HypothesesMakes the question precise and testable; decides what counts as evidence
Collect and analyse dataEvidence must be reliable, relevant and of sufficient size
Test statisticTurns the data into one number showing how far it is from H_0
Critical value and p-valueGive an objective rule, so the decision is not based on opinion
DecisionRejecting or not rejecting H_0 gives a clear conclusion
Interpret and reportLinks 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)
Fig. 4.17: Python code to create a simple dashboard
  1. 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}.
  2. Step 2: sample data. A pandas DataFrame with two columns, Month and Sales.
  3. Step 3: line plot. \texttt{px.line} draws Sales against Month with the title "Sales Over Time".
  4. Step 4: initialise the app. \texttt{app = dash.Dash()} creates the dashboard application.
  5. Step 5: layout. \texttt{html.Div} holds an \texttt{H1} title and a \texttt{dcc.Graph} that shows the figure.
  6. Step 6: run. \texttt{app.run(debug=True)} starts a local web server; the dashboard opens in the browser (or inside Colab).
Simple Sales Dashboard: Sales Over Time (Fig. 4.18)
What the dashboard shows. In the browser the Plotly chart is interactive: hovering shows exact values, and you can zoom.

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.
PointPredictive modelCausal model
Question answeredWhat will happen next?Why does it happen? What happens if we change X?
Based onPatterns and correlations in past dataCause-and-effect reasoning, experiments, hypothesis testing
ExamplePredict next month's sales, spam or not spam, tomorrow's temperatureDoes a breakfast programme cause higher attendance? Does exercise lower blood pressure?
UsesForecasting, recommendations, fraud alertsPolicy decisions, medicine, deciding which action to take
LimitationCorrelation is not causation; may fail if conditions change; can copy bias in dataNeeds careful experiments or controlled data; hard and costly; hidden factors can mislead

Applications of machine learning

FieldUse
HealthcarePredicts disease outbreaks and helps diagnose conditions
FinanceDetects fraudulent transactions to protect accounts
RetailPersonalises shopping experiences for customers
TransportationOptimises delivery routes to save time
AgricultureMonitors crop health for better yields
EducationTailors learning materials to individual needs
EntertainmentRecommends movies or songs based on user preferences

Formula sheet

Accuracy
\text{Accuracy}=\dfrac{\text{Correct predictions}}{\text{Total predictions}}=\dfrac{TP+TN}{TP+TN+FP+FN}
TP: true positives, TN: true negatives, FP: false positives, FN: false negatives
Units: a fraction or percentage
Precision
\text{Precision}=\dfrac{TP}{TP+FP}
Correct positive predictions out of all positive predictions
Units: a fraction or percentage
Recall
\text{Recall}=\dfrac{TP}{TP+FN}
Correct positive predictions out of all actual positives
Units: a fraction or percentage
F1 score
F1=2\cdot\dfrac{\text{Precision}\cdot\text{Recall}}{\text{Precision}+\text{Recall}}
Harmonic mean of precision and recall
Unit: a number from 0 to 1
Mean
\bar{x}=\dfrac{\sum x}{n}
\sum x: sum of all values, n: number of values
same unit as the data
Median position
\text{Median}=\left(\dfrac{n+1}{2}\right)^{\text{th}}\ \text{value of the ordered data}
For even n, take the mean of the two middle values
same unit as the data
Range
\text{Range}=x_{\max}-x_{\min}
Highest value minus lowest value
same unit as the data
Variance
\sigma^{2}=\dfrac{\sum (x-\bar{x})^{2}}{n}
\bar x: mean, n: number of values
square of the data unit
Standard deviation
\sigma=\sqrt{\dfrac{\sum (x-\bar{x})^{2}}{n}}
Square root of the variance
same unit as the data
Decision rule
\text{p-value}\le\alpha\Rightarrow \text{reject } H_0
\alpha: significance level, usually 0.05
Unit: probabilities (0 to 1)

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

1
The spam filter is used to do which of the following tasks:
  1. AIt helps to delete all emails
  2. BIt learns from past emails to identify spam emailsAnswer
  3. CIt increases the email storage capacity
  4. DIt marks all the emails to spam
Why

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.

2
Overfitting in a Machine Learning Model leads to:
  1. AThe model performs poorly on training data
  2. BThe model performs well on training data but poorly on new dataAnswer
  3. CThe model performs equally well on all types of data
  4. DThe model does not generate results at all
Why

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.

3
The feature engineering involves:
  1. ACollecting raw data
  2. BTransforming and selecting relevant data featuresAnswer
  3. CTesting the model's accuracy
  4. DCalculating the significance of the model
Why

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.

4
What is precision in a Machine Learning Model?
  1. AThe percentage of total correct predictions
  2. BThe measure of how many positive predictions are correctAnswer
  3. CThe measure of how well the model identifies all actual positive cases
  4. DThe percentage of training data used
Why

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.

5
How does continuous learning impact a Machine Learning Model?
  1. AIt reduces the model's accuracy over time
  2. BIt helps the model improve its performance by adapting to new dataAnswer
  3. CIt makes the model slower to process data
  4. DIt simplifies the model's decision-making process
Why

Continuous learning keeps the model learning from new data, so it stays accurate and improves its accuracy over time.

6
How does storytelling enhance the communication of data insights?
  1. ABy focusing solely on statistical analysis
  2. BBy using visuals and narrative to make data relatable and engagingAnswer
  3. CBy ignoring complex data patterns
  4. DBy minimizing the use of charts and graphs
Why

Data storytelling combines charts and graphs with a narrative, which makes data relatable, engaging and memorable. It uses more visuals, not fewer.

72026 Annual I, Set B, MCQ 7
Which of the following statements describe a Null hypothesis?
  1. AIt proposes that there is a significant effect or relationship between variables
  2. BIt assumes that observed differences are due to random chanceAnswer
  3. CIt is the hypothesis that researchers want to disprove
  4. DIt is a statistical method used to measure variability
Why

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.

8
In hypothesis testing P-Value indicates:
  1. AThe probability that the null hypothesis is true
  2. BThe probability that the results are due to some random chanceAnswer
  3. CThe significance level for the test statistics
  4. DThe confidence interval for the hypothesis
Why

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.

9
Why is it important to use visuals effectively in hypotheses testing?
  1. ATo replace the need for statistical analysis
  2. BTo present data in a more understandable manner and enhance communicationAnswer
  3. CTo make the data collection process easier
  4. DTo avoid need of a hypothesis formulation
Why

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.

10
In evaluating the credibility of a data story, which factor is least important?
  1. ASource of data
  2. BClarity of the visual presentation
  3. CThe time of day the data was collectedAnswer
  4. DRelevance to the topic
Why

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.

11
A model shows 98% accuracy, but precision and recall are both below 60%. What is the most likely issue?
  1. AThe model is underfitting
  2. BThe data is imbalancedAnswer
  3. CThe model is overfitting
  4. DLabels are missing in training data
Why

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.

12
A retail analyst wants to segment customers to discover hidden shopping patterns without any labeled categories. Which approach is most appropriate?
  1. ALogistic regression
  2. BClusteringAnswer
  3. CDecision trees
  4. DLinear regression
Why

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

12026 Annual I, Set B, Q.2 (xi) OR3 marks
Explain what 'Feature Engineering' is and give an example related to image classification.
Solution

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.

22026 Annual I, Set D, Q.2 (vi) OR3 marks
Describe the difference between 'Overfitting' and 'Underfitting' in Machine Learning.
Solution
OverfittingUnderfitting
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.
33 marks
What is the purpose of 'Test Data' in evaluating a Machine Learning model?
Solution

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.

43 marks
Define 'Model Assessment' and list two metrics used for it.
Solution

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.)
53 marks
What is the main goal of 'Data Visualization' in data analysis?
Solution

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.

62026 Annual I, Set D, Q.2 (xiii) OR3 marks
What is 'Data Storytelling' and why is it important?
Solution

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.

73 marks
How does continuous learning benefit a Machine Learning model?
Solution

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.

82026 Annual I, Set B, Q.2 (vii) OR3 marks
Explain the term 'Test-Train Split' and its importance in model training.
Solution

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.

93 marks
How does the significance level affect hypothesis testing?
Solution

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.

103 marks
Describe how you would identify and mitigate bias in a published data story.
Solution

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.

113 marks
What are the key steps in hypothesis testing and why are they important?
Solution
  1. Formulate H_0 and H_1.
  2. Collect data and analyse it.
  3. Calculate the test statistic.
  4. Compare it with the critical value and find the p-value.
  5. Decide to reject or not reject H_0.
  6. 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.

123 marks
Explain the role of standard deviation in understanding data variability.
Solution

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.

133 marks
How can descriptive statistics be used to summarize a large data set effectively?
Solution

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.

143 marks
How does the concept of statistical significance support or challenge conclusions in experimental research? Explain with an example.
Solution

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.

153 marks
How can data visualization bridge the gap between technical analysis and non-technical audiences? Explain with a real-world scenario.
Solution

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

12026 Annual I, Set D, Q.48 marks
Discuss the differences between Machine Learning models and Rule-based Algorithms, including their advantages and limitations.
Solution

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

PointMachine learningRule-based
Source of rulesLearned from dataWritten by people
AdaptabilityAdapts and improves with more dataFixed until updated by hand
ProblemsComplex, unexpected, unstructuredSimple, well-defined
Data neededLarge datasetsLittle data
TransparencyHard to interpretEasy to explain
ResourcesHigh computing powerLow 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).

28 marks
Explain the process of model building in Machine Learning, including data collection, preprocessing, training, and evaluation.
Solution

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.

38 marks
Compare and contrast 'Predictive Models' and 'Causal Models,' discussing their uses and limitations.
Solution

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

PointPredictive modelCausal model
QuestionWhat will happen?Why, and what if we change something?
Based onCorrelations and patterns in past dataCause-and-effect reasoning and experiments
GoalAccurate forecastsUnderstanding and decision-making
ExampleIce-cream sales predict sunburn casesHot sun causes both ice-cream sales and sunburn
StrengthWorks with large observational data, fastTells which action will change the outcome
WeaknessCorrelation is not causationHarder 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.

48 marks
Discuss how formulating good research questions influences the quality of data analysis. Provide an example of how a well-formulated question led to meaningful insights in a study.
Solution

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.

  1. 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?
  2. Relevant datasets: student attendance records, breakfast programme participation data, demographic data (grade level, family income).
  3. 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.
  4. 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.

52026 Annual I, Set B, Q.48 marks
Examine the process of hypothesis formulation and testing in a real-world context. How do null and alternative hypotheses guide research and decision-making? Illustrate with a relevant example.
Solution

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

  1. Question: Can exercising for six weeks lower blood pressure?
  2. Hypotheses: H_0: exercise does not affect blood pressure. H_1: exercise lowers blood pressure.
  3. Data: blood pressure of people before and after six weeks of exercise; the average reduction was 8 mmHg.
  4. Test: a statistical test gives p-value =0.005, only a 0.5% chance of such a drop by luck.
  5. Decision: 0.005<0.05, so reject H_0 and accept H_1.
  6. 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.

68 marks
Critique a published data story for its use of clarity and accuracy. Identify any misleading or biased elements and suggest improvements.
Solution

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.

72026 Annual I, Set B, Q.2 (iv)2026 Annual I, Set D, Q.2 (vii) OR8 marks
Explore the role of p-values in hypothesis testing. How do they help determine the significance of research findings, and what are their limitations?
Solution

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.

88 marks
Analyze the steps of simple hypothesis testing and their importance in validating research findings. How does each step contribute to drawing accurate conclusions?
Solution

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?

StepWhat is doneHow it helps an accurate conclusion
1. Formulate hypothesesH_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 analyseMeasure 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 statisticCompute, for example, a t-statistic.Summarises how far the data deviates from H_0 in one number.
4. Compare with the critical valueIs the statistic beyond the critical value?Gives an objective boundary for rejecting H_0.
5. Determine the p-valueFind the probability of such data if H_0 were true.Measures the strength of evidence; compared with \alpha=0.05.
6. DecideReject 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 decisionsFor example, provide coffee in the office.Turns the result into action.
8. Interpret in contextExplain 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 visualsCharts 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.

98 marks
Discuss the challenges in ensuring data accuracy and relevance in a data story. How can these challenges be addressed to improve the credibility of the data story?
Solution

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.

108 marks
Evaluate how feedback can be used to refine data storytelling techniques. Provide examples of how constructive criticism can lead to more effective data presentations.
Solution

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 receivedImprovement 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.

118 marks
Discuss the challenges in ensuring data accuracy and relevance in a data story. How can these challenges be addressed to improve the credibility of the data story?
Solution

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.

128 marks
Evaluate how feedback can be used to refine data storytelling techniques. Provide examples of how constructive criticism can lead to more effective data presentations.
Solution

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 receivedImprovement 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.

13 marks
Define data. Differentiate between structured, semi-structured and unstructured data with examples.
Solution

Data is a collection of raw facts and figures collected from different sources.

StructuredSemi-structuredUnstructured
Organised in rows and columns (tables)Organised in a specific format but with no fixed schemaNo predefined structure
Easy to search and countPartly searchable using tags or keysHard to search directly
Spreadsheets, databases, CSV filesXML and JSON filesVideos, emails, web pages, images, audio
23 marks
Differentiate between nominal and ordinal data with examples.
Solution

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.

33 marks
What is reinforcement learning? Give one algorithm and one application.
Solution

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.

43 marks
A model is tested on 100 images for the class Cat: TP = 40, FP = 10, FN = 20, TN = 30. Calculate its accuracy, precision, recall and F1 score.
Solution
  1. Accuracy: correct predictions (TP + TN) out of all 100.
    \text{Accuracy}=\dfrac{40+30}{100}=0.70=70\%
  2. Precision: correct Cat predictions out of all Cat predictions (40 + 10 = 50).
    \text{Precision}=\dfrac{40}{40+10}=0.80
  3. Recall: correct Cat predictions out of all real cats (40 + 20 = 60).
    \text{Recall}=\dfrac{40}{40+20}=0.67
  4. 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.

\text{Accuracy}=70\%,\ \text{Precision}=0.80,\ \text{Recall}=0.67,\ F1=0.73
53 marks
What is the F1 score? Why is it preferred over accuracy for imbalanced data?
Solution

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.

63 marks
Differentiate between Type I and Type II errors with an example.
Solution
Type I errorType II error
Rejecting H_0 when it is actually trueFailing to reject H_0 when it is actually false
A false alarm: we find an effect that is not thereA miss: we fail to find an effect that is there
Its probability equals the significance level \alphaReduced by increasing the sample size (more power)
Coffee example: concluding coffee improves productivity when it does notCoffee example: concluding coffee has no effect when it actually improves productivity
73 marks
What is a confidence interval? Explain with an example.
Solution

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.

83 marks
What is meant by the power of a test? How does sample size affect it?
Solution

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.

93 marks
Define test statistic and critical value. How are they used to reach a decision?
Solution

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.

103 marks
Differentiate between independent and dependent variables with the help of a hypothesis.
Solution
  • 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.

113 marks
Name any three tools used for data visualization and state the use of each.
Solution
  • 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.

123 marks
What is a dashboard? Name the Python framework used to create it.
Solution

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.

133 marks
Differentiate between classification, regression and clustering algorithms.
Solution
ClassificationRegressionClustering
Sorts data into categories (labels)Predicts a continuous numerical valueGroups similar data points together
Supervised (needs labels)Supervised (needs labels)Unsupervised (no labels)
Example: cat, dog or horse; spam or not spamExample: house price, temperature, marks from study hoursExample: customer segmentation with K-Means
143 marks
Why are neural networks suitable for unstructured data such as images?
Solution

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.

153 marks
Find the range, variance and standard deviation of the data 4, 8, 6, 5, 7.
Solution
  1. Range: highest minus lowest.
    8-4=4
  2. Mean of the 5 values (sum 30).
    \bar x=\dfrac{30}{5}=6
  3. 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
  4. Variance is the average of the squared differences.
    \sigma^2=\dfrac{10}{5}=2
  5. Standard deviation is the square root of the variance.
    \sigma=\sqrt{2}=1.41
\text{Range}=4,\ \sigma^2=2,\ \sigma\approx1.41
163 marks
What are percentiles and histograms? How do they describe data?
Solution

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.

173 marks
How is machine learning different from human learning?
Solution

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.

188 marks
Explain supervised, unsupervised and reinforcement learning. Give one algorithm and one real-life example of each.
Solution

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

PointSupervisedUnsupervisedReinforcement
DataLabelledUnlabelledExperience from environment
FeedbackCorrect answer for each exampleNoneReward or penalty
GoalPredict label or valueFind groups or patternsMaximise reward
AlgorithmLinear regressionK-MeansQ-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.

198 marks
Explain accuracy, precision, recall and F1 score with formulas. Write a Python program to calculate them from actual and predicted labels.
Solution

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.73
Output

Interpretation

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.

208 marks
Write a Python program to find the mean, median, mode, range, variance and standard deviation of the marks of 10 students. Explain each measure.
Solution

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.23
Output

Explanation 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.

218 marks
Write and explain the Python code that uses linear regression to visualize study hours against marks. What output does it produce?
Solution

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 graph

Explanation

  • 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.0
Output

The 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.

228 marks
What is a dashboard? Write Python code to create a simple sales dashboard using Dash and Plotly, and explain each step.
Solution

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.

238 marks
Explain the terms test statistic, confidence interval, Type I error, Type II error, power, significance level and sample size used in hypothesis testing, with the help of an example.
Solution

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.
DecisionH_0 trueH_0 false
Reject H_0Type I errorCorrect (power)
Fail to reject H_0CorrectType 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.

248 marks
Describe the types of data used in data science and machine learning, with a description and example of each.
Solution

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.

TypeDescriptionExamples
NumericalQuantitative values that can be measured or countedMarks, salary, age
CategoricalDiscrete values or labels; nominal (no order) or ordinal (ordered)Nominal: gender, colour. Ordinal: small, medium, large
BooleanOnly two values, 0 or 1True/False, Yes/No
TextA sequence of charactersReviews, feedback, descriptions
Time seriesValues recorded over a long period in time orderStock prices, weather data
ImagePixel valuesX-rays, ultrasound, photographs
AudioSound wavesSpeech, music
StructuredRows and columns (tables)Spreadsheets, databases
Semi-structuredSpecific format but no fixed schemaXML, JSON files
UnstructuredNo predefined structureVideos, 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.

2026 Annual I, Set B, MCQ 71 mark
Which hypothesis assumes there is no effect or relationship between variables?
  1. ANull Hypothesis (H_0)Answer
  2. BCause-and-effect Hypothesis
  3. CAlternative Hypothesis (H_1)
  4. DResearch Hypothesis
Why

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.

2026 Annual I, Set B, MCQ 81 mark
Which type of learning uses labelled data?
  1. ASelf-Learning
  2. BReinforcement Learning
  3. CUnsupervised Learning
  4. DSupervised LearningAnswer
Why

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.

2026 Annual I, Set B, Q.2 (i) OR1x3 = 3 marks
Write down any three advantages of machine learning.
Solution

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.
2026 Annual I, Set B, Q.2 (iv)3 marks
Briefly discuss the role of p-values in hypothesis testing.
Solution

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.
2026 Annual I, Set B, Q.2 (vii) OR3 marks
Briefly discuss the concept of a test-train split in model building.
Solution

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.

2026 Annual I, Set B, Q.2 (xi) OR1x3 = 3 marks
Why is feature engineering important in machine learning? Support your answer with three points.
Solution

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.
2026 Annual I, Set B, Q.2 (xiii) OR1x3 = 3 marks
What are mean, median, and mode in descriptive statistics?
Solution

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.
2026 Annual I, Set B, Q.42+3 = 5 marks
Explain the process of hypothesis formulation. Discuss the role of the null and the alternative hypothesis with suitable example.
Solution

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.
2026 Annual I, Set D, MCQ 61 mark
What does a low p-value indicate?
  1. AStrong evidence against H_0Answer
  2. BWeak evidence against H_0
  3. CResults due to chance
  4. DNull hypothesis is always accepted
Why

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.

2026 Annual I, Set D, MCQ 71 mark
Which of the following best describes Machine Learning?
  1. AFixed instructions only
  2. BManual data organizing
  3. CLearn from data to decideAnswer
  4. DStore data in databases
Why

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.

2026 Annual I, Set D, Q.2 (iii)1.5+1.5 = 3 marks
What is the difference between supervised learning and unsupervised learning?
Solution
Supervised learningUnsupervised 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.
2026 Annual I, Set D, Q.2 (iv)1.5+1.5 = 3 marks
What is the difference between a null hypothesis (H_0) and an alternative hypothesis (H_1)?
Solution
Null hypothesis H_0Alternative 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.
2026 Annual I, Set D, Q.2 (vi) OR1.5+1.5 = 3 marks
Explain briefly overfitting and underfitting in model building using machine learning?
Solution

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.

2026 Annual I, Set D, Q.2 (vii) OR1.5+1.5 = 3 marks
Briefly discuss the role of P-value in hypothesis testing with examples.
Solution

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.

2026 Annual I, Set D, Q.2 (xiii) OR2+1 = 3 marks
What is meant by data storytelling? Give one example.
Solution

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.

2026 Annual I, Set D, Q.42.5+2.5 = 5 marks
Explain the advantages and limitations of Machine Learning compared to Rule-Based algorithms. Provide at least two points for each.
Solution

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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. Mean, median, mode and standard deviation. (short)
    2026 Set B Q.2 (xiii) OR; book SRQs 12 and 13.
    Go to answer
  9. 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
  10. 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

Mark this unit as done to fill the Class 12 Computer Science ring.

Next, unit 5
Applications of computer science

© 2026 FBISE Fold. Independent study notes, not affiliated with the Federal Board of Intermediate and Secondary Education.