Certification short course · AFRETEC · University of Rwanda
AI and Big Data Analytics
Detailed course notes, practical workshops and practice guide
Aligned with the Certificate in AI for Africa (Carnegie Mellon University Africa)
- 20sessions in 4 weeks
- 5practical workshops
- 22figures and diagrams
- 6certificate courses mapped
December 2026
A companion study guide. It is not official University of Rwanda or Carnegie Mellon University Africa material.
About These Notes
These notes accompany the four-week AI and Big Data Analytics short course. They follow the proposed 20-session syllabus (five sessions per week, 3.5 hours each) and are written so that a participant can read them before a session, follow along during the lab, and revise afterwards.
These notes are a companion study guide written to support the proposed syllabus. They are not the official University of Rwanda course material, and the instructors may change the order or depth of topics.
How each session is organized
Every session chapter has the same structure:
- Learning objectives: what you should be able to do by the end.
- Theory: the key ideas, explained in plain language with examples from Rwanda and Africa.
- Hands-on lab: Python code you can run in Google Colab, with comments.
- Key takeaways: a short summary to revise from.
- Practice exercises: tasks to try on your own.
How to study with these notes
- Skim the objectives and takeaways before the session.
- Type the code yourself instead of copying and pasting. Typing builds understanding faster than reading.
- Break the code on purpose (change a value, delete a line) and observe what happens.
- Finish the practice exercises the same evening while the topic is fresh.
- Keep a personal notebook of mistakes and fixes.
Course map
| Week | Theme | Main skills |
|---|---|---|
| 1 | Foundations and data handling | Python, NumPy, pandas, loading and cleaning data |
| 2 | Statistics and visualization | Descriptive statistics, probability, EDA, charts, dashboards |
| 3 | Machine learning | Regression, classification, trees, clustering, model evaluation, neural networks |
| 4 | Big data, applied AI and capstone | Spark, SQL, cloud, generative AI, responsible AI, capstone project |
Setting up your environment
You do not need to install anything. All labs run in Google Colab, a free service from Google that runs Python in your web browser.
- Open a browser (Chrome is recommended) and go to
colab.research.google.com. - Sign in with a Google account.
- Click New notebook.
- A notebook is made of cells. A code cell holds Python code and a text cell holds notes. Press Shift + Enter to run a cell.
- To save your work, use File > Save a copy in Drive.
To test your setup, type this in a code cell and run it:
print("Muraho, data science!")
import sys
print(sys.version)
If you prefer to work on your laptop, install
Anaconda or Python 3.11+ with
pip install jupyter pandas numpy matplotlib seaborn scikit-learn,
then start Jupyter with the command jupyter notebook.
Working with data in Colab
Colab starts empty each time, so you need to load your files. There are two ways:
# Option 1: upload a file from your computer
from google.colab import files
uploaded = files.upload() # a file picker opens
# Option 2: mount your Google Drive
from google.colab import drive
drive.mount('/content/drive') # then read files from /content/drive/MyDrive/
Classroom rules for data work
- Always keep an untouched copy of the raw data. Do your cleaning on a copy.
- Write comments that explain why, not only what.
- Never share personal or sensitive data. Use public or anonymized data in class.
- Ask questions early. Everyone starts from a different level, and that is normal.
A note on datasets
The labs use small datasets so they run quickly. Where a lab says “a public dataset”, you can use data from the National Institute of Statistics of Rwanda (NISR), the World Bank Open Data portal, Kaggle, or the DHS Program. To keep the code self-contained, many examples create small sample data inside the notebook. Treat the numbers in those examples as illustrative, not as official statistics.
Alignment with the Certificate in AI for Africa
These notes have been updated to match the program description of the Certificate in AI for Africa from Carnegie Mellon University Africa (CMU-Africa), as supplied for this course. The notes are a companion study guide and are not official CMU-Africa material. Always confirm current details with CMU-Africa.
The program at a glance
| Item | Details (from the program description) |
|---|---|
| Structure | Six courses, each with 14 or 15 lessons of about three hours (about 45 hours per course) |
| Pace | At least five to six hours per week |
| Awards | A digital badge for each course and a sharable, verifiable certificate for completing all six; not for university credit |
| Design | Courses designed by Carnegie Mellon University professors of engineering |
| Perspective and context track | Artificial Intelligence: Past, Present and Future; AI and Machine Learning in Africa |
| Technical track | Python for AI; Mathematical Foundations of Machine Learning; Machine Learning Essentials; Applied Generative AI |
| Prerequisites | Basic linear algebra, probability and statistics, and computer programming; a laptop or desktop and reliable internet |
| Timeline listed | Applications and recommendations: 15 October to 15 November 2026; new cohort starts 17 January 2027 (check CMU-Africa for later rounds) |
| Contact | cmuafricacerts@andrew.cmu.edu; CMU-Africa, Regional ICT Center of Excellence Building, Kigali Innovation City, Bumbogo, BP 6150, Kigali, Rwanda |
Learning outcomes and where these notes cover them
| Learners will be able to… | Where in these notes |
|---|---|
| Demonstrate knowledge of the purpose, capabilities and limitations of AI tools and techniques | Week 1, Session 1; Module S1; Week 4, Session 3 |
| Apply foundational analytical and technical skills for AI-driven solutions in Africa | Weeks 1 and 2; Module S2 |
| Develop AI models and solutions using current tools, frameworks and best practices | Week 3; Week 4; Module S3; Module S5 |
| Turn real-world challenges into data-driven AI solutions that are effective, relevant and deployable | Module S4; the practical workshops; the capstone |
| Determine the impact of AI solutions using appropriate metrics, validation techniques and critical thinking | Week 3, Sessions 2 and 3; Module S4; Week 4, Session 4 |
How the six courses map to these notes
| Certificate course | Main coverage here | Added in the supplementary modules |
|---|---|---|
| Artificial Intelligence: Past, Present and Future | Week 1, Session 1 | Module S1 |
| AI and Machine Learning in Africa | Rwanda and Africa examples, case studies | Module S2 |
| Python for AI | Week 1, Sessions 2 to 5 | Python for linear algebra and optimization in Module S3 |
| Mathematical Foundations of Machine Learning | Week 2, Sessions 1 and 2 | Module S3 (linear algebra, calculus, optimization) |
| Machine Learning Essentials | Week 3 | Module S4 (validation and impact) |
| Applied Generative AI | Week 4, Session 3 | Module S5 (retrieval-augmented generation and evaluation) |
Career pathways
The certificate supports early-career learners seeking internships and entry-level roles, and mid-career technical professionals, in areas such as machine learning applications, AI application development, AI product support, AI research and innovation, and related AI fields. A portfolio of the workshops and capstone in these notes is good evidence of skills for such roles.
Prerequisite self-check
| Skill | Quick check: can you do this? |
|---|---|
| Linear algebra | Multiply a 2×2 matrix by a vector; explain what a dot product measures |
| Probability and statistics | Compute a mean and standard deviation; explain a conditional probability |
| Programming | Write a Python function with a loop and a condition |
| Tools | Open a Google Colab notebook and run a cell |
If any item is hard, read Module S3 and Week 1, Session 2 first.
Week 1: Foundations and Data Handling
Goal of the week: understand the AI and data landscape and become productive with Python for data work. By Friday you will be able to load data from several sources, clean it, and explain what you did.
Session 1: Introduction to AI, Machine Learning and Big Data
Learning objectives
- Define artificial intelligence, machine learning, deep learning, data science and big data, and explain how they relate.
- Describe the five Vs of big data.
- Walk through the data science lifecycle.
- Give examples of AI and data applications in Rwanda and Africa.
Theory
Artificial intelligence (AI) is the field of building computer systems that perform tasks that normally need human intelligence, such as understanding language, recognizing images, making predictions and making decisions.
Machine learning (ML) is a part of AI in which a system learns patterns from data instead of following rules written by a programmer. A spam filter is a good example. Rather than writing thousands of rules about spam, we show the computer many emails labeled “spam” and “not spam”, and it learns the patterns.
Deep learning (DL) is a part of machine learning that uses neural networks with many layers. It is behind modern speech recognition, image recognition and large language models.
Data science is the broader practice of getting value from data. It combines statistics, programming and domain knowledge. A data scientist asks a question, gathers and cleans data, analyzes it, builds models where useful, and communicates results.
A simple way to remember the relationship: deep learning is inside machine learning, which is inside AI. Data science overlaps with all of them.
Traditional programming versus machine learning
| Traditional programming | Machine learning | |
|---|---|---|
| Input | Data and rules | Data and answers |
| Output | Answers | Rules (a model) |
| Example | A tax calculator with fixed formulas | A model that learns to predict loan default from past loans |
Big data and the five Vs
Big data describes datasets that are too large, too fast or too varied for traditional tools. It is usually described by five characteristics.
| V | Meaning | Example |
|---|---|---|
| Volume | The amount of data | Millions of mobile money transactions per day |
| Velocity | The speed data arrives | Live sensor readings from weather stations |
| Variety | Different forms of data | Tables, text messages, images, GPS traces |
| Veracity | The quality and trustworthiness of data | Missing or wrongly entered health records |
| Value | The usefulness of the insight | A model that helps a farmer decide when to plant |
The data science lifecycle
- Define the problem. What decision will this analysis support?
- Collect data. Files, databases, APIs, sensors, surveys.
- Clean and prepare data. Fix errors, handle missing values.
- Explore the data. Summaries and charts to find patterns.
- Model. Build statistical or machine learning models.
- Evaluate. Check that the model works on new data.
- Deploy and communicate. Share results, build dashboards or applications.
- Monitor. Check that the model keeps working as the world changes.
In real projects most of the time goes into steps 1 to 3. A common rule of thumb says data preparation takes the majority of a project, so learning it well pays off.
Examples from Rwanda and Africa
- Health: Rwanda uses digital health information systems to track services and disease trends. Analysis of such data can help plan staff and supplies. Drone deliveries of medical supplies have also drawn international attention to Rwanda’s technology adoption.
- Agriculture: Satellite images, weather data and soil data can help estimate crop yields and warn farmers about pests or drought.
- Finance and mobile money: Transaction data can support fraud detection, credit scoring for people without a bank history, and financial inclusion.
- Transport and cities: Mobility data can help plan routes and reduce congestion in cities such as Kigali.
- Language: Researchers are building speech and text tools for Kinyarwanda, which is a lower-resource language with limited data compared with English.
These examples show that the field is not only about big companies. Local problems and local data can lead to valuable solutions.
Hands-on lab: your first notebook
Open Google Colab and create a notebook named
week1_session1. Run each block below in its own cell.
# A tiny "model by rules" versus "model by learning" demonstration
# Rule-based: we write the rule ourselves
def is_spam_rule(message):
return "win money" in message.lower()
print(is_spam_rule("Win money now!")) # True
print(is_spam_rule("Meeting at 3pm")) # False
The rule works only for the exact phrase we chose. Now see a very small learned model.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
messages = [
"win money now", "free prize claim now", "urgent claim your prize",
"meeting at 3pm", "lunch tomorrow", "project report attached",
]
labels = [1, 1, 1, 0, 0, 0] # 1 = spam, 0 = not spam
vec = CountVectorizer()
X = vec.fit_transform(messages) # turn text into numbers
model = MultinomialNB().fit(X, labels) # learn from examples
test = ["claim your free money", "report for the meeting"]
print(model.predict(vec.transform(test))) # expected: [1 0]
The model was never given a rule such as “free means spam”. It learned the pattern from examples. This is machine learning in miniature.
Key takeaways
- AI is the broad field, machine learning learns from data, and deep learning uses multi-layer neural networks.
- Big data is described by volume, velocity, variety, veracity and value.
- The data science lifecycle starts with a clear question, not with an algorithm.
- Local data and local problems offer real opportunities in Rwanda and Africa.
Practice exercises
- In your own words, explain the difference between traditional programming and machine learning, using an example from your own field.
- Pick one problem in your community. List the data you would need and where it might come from.
- For the problem in exercise 2, write one possible risk (for example privacy or bias).
- Add three more spam and three more non-spam messages to the lab model. Does it still predict correctly?
Session 2: Python Fundamentals
Learning objectives
- Write Python programs using variables, data types, operators and printing.
- Use lists, tuples, dictionaries and sets.
- Control program flow with
if,forandwhile. - Write and call functions.
Theory
Python is the most widely used language in data science because it is readable, has a huge community and has excellent libraries. Think of Python as the language and libraries such as pandas and scikit-learn as the tools.
Variables and data types
A variable is a name that points to a value. Python decides the type automatically.
name = "Uwase" # str (text)
age = 24 # int (whole number)
height_m = 1.65 # float (decimal number)
is_student = True # bool (True or False)
print(name, age, height_m, is_student)
print(type(age), type(height_m))
Common operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * / |
Arithmetic | 7 / 2 |
3.5 |
// |
Integer division | 7 // 2 |
3 |
% |
Remainder | 7 % 2 |
1 |
** |
Power | 2 ** 3 |
8 |
== != |
Equal, not equal | 3 == 3 |
True |
< > <=
>= |
Comparison | 5 > 2 |
True |
and or not |
Logic | True and False |
False |
Text (strings) can be combined and formatted:
city = "Kigali"
population_millions = 1.7
print(f"{city} has about {population_millions} million people") # f-string
print(city.upper(), city.lower(), len(city))
Collections
Data science depends on collections of values.
# List: ordered, changeable
prices = [500, 1000, 2000, 5000]
prices.append(10000)
print(prices[0], prices[-1], prices[1:3]) # indexing and slicing
# Tuple: ordered, fixed
location = (-1.9441, 30.0619) # latitude, longitude
# Dictionary: key to value pairs
student = {"name": "Mugisha", "district": "Huye", "score": 78}
print(student["district"])
student["score"] = 82 # update a value
# Set: unique values only
districts = {"Huye", "Musanze", "Huye", "Rubavu"}
print(districts) # duplicates removed
Python counts positions from zero, so
prices[0] is the first element. Negative positions count
from the end.
Control flow
Conditions let the program choose.
score = 67
if score >= 80:
grade = "A"
elif score >= 60:
grade = "B"
else:
grade = "C"
print(grade)
Loops repeat actions.
# for loop over a list
for p in prices:
print(p, "RWF")
# for loop with range
for i in range(1, 6):
print(i, i ** 2)
# while loop
count = 3
while count > 0:
print("countdown", count)
count -= 1
A list comprehension is a compact way to build a list:
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
big = [p for p in prices if p >= 2000] # [2000, 5000, 10000]
Functions
A function packages code so you can reuse it.
def convert_to_usd(amount_rwf, rate=1400):
"""Convert Rwandan francs to US dollars (illustrative rate)."""
return amount_rwf / rate
print(convert_to_usd(14000)) # 10.0
print(convert_to_usd(14000, rate=1300))
Good functions do one thing, have a clear name, and include a short description called a docstring.
Reading errors
Errors are normal. Read the last line of the message first, because it names the error type.
| Error | Common cause |
|---|---|
SyntaxError |
A missing colon, bracket or quote |
NameError |
Using a variable that does not exist |
TypeError |
Mixing types, for example adding text and a number |
IndexError |
Asking for a list position that does not exist |
KeyError |
Asking for a dictionary key that does not exist |
IndentationError |
Wrong spacing inside blocks |
Hands-on lab: a small data task in pure Python
# Daily sales (RWF) of a small shop for a week
sales = {"Mon": 42000, "Tue": 38000, "Wed": 51000, "Thu": 47000,
"Fri": 69000, "Sat": 82000, "Sun": 30000}
total = sum(sales.values())
average = total / len(sales)
best_day = max(sales, key=sales.get)
print(f"Total: {total:,} RWF")
print(f"Average: {average:,.0f} RWF")
print(f"Best day: {best_day}")
# Flag days below average
below = [day for day, value in sales.items() if value < average]
print("Below average:", below)
Key takeaways
- Variables store values; Python infers the type.
- Lists, dictionaries, tuples and sets organize data.
if,forandwhilecontrol the flow; comprehensions shorten loops.- Functions make code reusable and readable.
- Read error messages from the bottom line.
Practice exercises
- Write a function
bmi(weight_kg, height_m)that returns the body mass index. - Given a list of ten exam scores, compute the mean, maximum and minimum without using libraries.
- Create a dictionary of five districts and their populations (use any approximate numbers), then print the district with the largest value.
- Use a list comprehension to convert a list of prices in RWF to dollars.
Session 3: NumPy and pandas
Learning objectives
- Create and manipulate NumPy arrays.
- Create pandas Series and DataFrames.
- Select, filter, sort, group and merge data.
Theory: why NumPy and pandas?
Python lists are flexible but slow for large numerical work. NumPy adds fast arrays and mathematical functions. pandas is built on NumPy and gives you the DataFrame, a table with named columns, similar to an Excel sheet but programmable and far more powerful. Almost every data analysis in Python starts with pandas.
NumPy arrays
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
print(a + b) # element by element: [11 22 33 44]
print(a * 2) # [20 40 60 80]
print(a.mean(), a.std(), a.max())
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.shape) # (2, 3): 2 rows, 3 columns
print(m[1, 2]) # row 1, column 2 -> 6
print(m.T) # transpose
print(np.zeros((2, 2)), np.arange(0, 10, 2))
Operations work on the whole array at once. This is called vectorization, and it is both shorter and much faster than writing loops.
Boolean masks select values that meet a condition:
temps = np.array([22.5, 25.1, 19.8, 30.2, 27.4])
print(temps[temps > 25]) # [25.1 30.2 27.4]
pandas Series and DataFrames
A Series is one column; a DataFrame is a table made of Series.
import pandas as pd
data = {
"district": ["Gasabo", "Huye", "Musanze", "Rubavu", "Nyagatare"],
"province": ["Kigali", "South", "North", "West", "East"],
"crop_tonnes": [320, 540, 610, 450, 720],
"rainfall_mm": [980, 1100, 1350, 1250, 820],
}
df = pd.DataFrame(data)
print(df)
(These numbers are illustrative, not official figures.)
First look at any DataFrame with these methods:
df.head() # first 5 rows
df.tail(3) # last 3 rows
df.shape # (rows, columns)
df.info() # column names, types, non-null counts
df.describe() # summary statistics for numeric columns
df.columns # list of column names
df.dtypes # data types
Selecting data
df["district"] # one column (a Series)
df[["district", "crop_tonnes"]] # several columns
df.loc[0] # row by label
df.loc[0:2, "district":"province"] # rows and columns by label
df.iloc[1:3, 0:2] # rows and columns by position
Use loc for labels and iloc for integer
positions. Remember that loc slices include the end label,
while iloc slices exclude the end.
Filtering and sorting
high = df[df["crop_tonnes"] > 500]
print(high)
# several conditions: use & (and), | (or), and parentheses
wet_high = df[(df["rainfall_mm"] > 1000) & (df["crop_tonnes"] > 500)]
df.sort_values("crop_tonnes", ascending=False)
df[df["province"].isin(["North", "South"])]
Creating and changing columns
df["tonnes_per_100mm"] = df["crop_tonnes"] / df["rainfall_mm"] * 100
df["size_class"] = np.where(df["crop_tonnes"] >= 500, "high", "low")
df = df.rename(columns={"crop_tonnes": "yield_t"})
df = df.drop(columns=["size_class"])
Grouping and aggregating
groupby follows the pattern split, apply,
combine: split rows into groups, compute a summary for each
group, and combine the results.
by_province = df.groupby("province")["yield_t"].agg(["mean", "max", "count"])
print(by_province)
df.groupby("province").agg(
avg_yield=("yield_t", "mean"),
avg_rain=("rainfall_mm", "mean"),
)
Merging tables
Real data is spread across tables. A merge joins tables on a shared key, like a SQL join.
population = pd.DataFrame({
"district": ["Gasabo", "Huye", "Musanze", "Kayonza"],
"population": [530000, 330000, 370000, 350000],
})
left = df.merge(population, on="district", how="left") # keep all rows of df
inner = df.merge(population, on="district", how="inner") # only matching rows
print(left)
how= |
Meaning |
|---|---|
inner |
Keep only rows that match in both tables |
left |
Keep all rows from the left table |
right |
Keep all rows from the right table |
outer |
Keep all rows from both tables |
To stack tables with the same columns on top of each other, use
pd.concat([df1, df2]).
Hands-on lab
Using the district DataFrame above:
- Show the five rows with
head()and the structure withinfo(). - Add a column
yield_per_personafter merging population. - Find the province with the highest average yield.
- Sort the districts by rainfall and print the top three.
Key takeaways
- NumPy provides fast arrays; operations are vectorized.
- A DataFrame is a table; start every project with
head,infoanddescribe. - Use boolean conditions to filter,
groupbyto summarize, andmergeto combine tables.
Practice exercises
- Create a DataFrame of ten students with name, class and score. Find the average score per class.
- Filter students with a score above the class average.
- Merge a second table of student ages and compute the correlation
between age and score using
df["age"].corr(df["score"]).
Session 4: Collecting and Loading Data
Learning objectives
- Read data from CSV, Excel, JSON and databases.
- Understand how a web API returns data.
- Save cleaned data to files.
Theory: where data comes from
| Source | Examples | Typical format |
|---|---|---|
| Files | Exports from systems, spreadsheets, survey data | CSV, Excel, JSON |
| Databases | Business and government systems | SQL tables |
| APIs | Weather services, open data portals, social platforms | JSON |
| Web pages | Public tables on websites | HTML (scraping, with permission) |
| Sensors and logs | IoT devices, servers, mobile apps | Streams, text logs |
When you collect data, always ask: Who produced it? When? How was it measured? Do I have permission to use it?
Reading CSV files
CSV stands for comma-separated values. It is the most common exchange format.
import pandas as pd
df = pd.read_csv("data.csv")
# useful options
df = pd.read_csv(
"data.csv",
sep=",", # delimiter (use ";" or "\t" if needed)
encoding="utf-8", # try "latin-1" if you get decoding errors
na_values=["NA", "n/a", "-"],
parse_dates=["date"],
usecols=["date", "district", "cases"],
)
To practise without a file, create one:
from io import StringIO
raw = """date,district,cases
2026-01-01,Huye,12
2026-01-02,Huye,15
2026-01-01,Musanze,9
2026-01-02,Musanze,
"""
df = pd.read_csv(StringIO(raw), parse_dates=["date"])
print(df)
Reading Excel and JSON
excel_df = pd.read_excel("report.xlsx", sheet_name="Sheet1")
all_sheets = pd.read_excel("report.xlsx", sheet_name=None) # dict of sheets
json_df = pd.read_json("data.json")
Excel files often hide problems: merged cells, titles above the table
and notes below it. Use skiprows, header and
usecols to read only the real table.
Reading from a database with SQL
SQL (Structured Query Language) is the standard language for relational databases. A basic query looks like this:
SELECT district, SUM(cases) AS total_cases
FROM health_records
WHERE date >= '2026-01-01'
GROUP BY district
ORDER BY total_cases DESC;
You can run SQL from Python. The example uses SQLite, which needs no server:
import sqlite3
import pandas as pd
conn = sqlite3.connect(":memory:") # temporary database in memory
df.to_sql("health_records", conn, index=False, if_exists="replace")
query = """
SELECT district, SUM(cases) AS total_cases
FROM health_records
GROUP BY district
"""
result = pd.read_sql(query, conn)
print(result)
conn.close()
For other databases (PostgreSQL, MySQL) you use a library such as
SQLAlchemy to create a connection, then call pd.read_sql in
the same way.
Using web APIs
An API (Application Programming Interface) lets programs ask a service for data. Most web APIs return JSON, which looks like nested Python dictionaries and lists.
import requests
url = "https://api.worldbank.org/v2/country/RW/indicator/SP.POP.TOTL"
params = {"format": "json", "per_page": 5}
response = requests.get(url, params=params, timeout=30)
print(response.status_code) # 200 means success
payload = response.json()
records = payload[1] # the World Bank API returns [metadata, data]
df_api = pd.DataFrame(records)[["date", "value"]]
print(df_api)
Important API ideas:
- Status codes: 200 success, 404 not found, 401 or 403 not allowed, 429 too many requests.
- Parameters: options you add to the request, such as dates or country.
- Keys: many APIs need a secret key. Never put keys in code you share.
- Rate limits: services limit how often you may ask. Be polite and cache results.
- Terms of use: always check the license before using or sharing the data.
Always use timeout and check the status code so your
program does not freeze or fail silently. This lab needs internet
access, and the service’s output format can change, so read the response
before you rely on it.
Saving your results
df.to_csv("clean_data.csv", index=False)
df.to_excel("clean_data.xlsx", index=False)
df.to_json("clean_data.json", orient="records")
df.to_parquet("clean_data.parquet") # compact format for large data (needs pyarrow)
Hands-on lab
- Read the sample CSV above from the
StringIOstring. - Load it into an SQLite table and write a SQL query for the average cases per district.
- Call the World Bank API and plot the population of Rwanda over
several years (hint:
df_api.plot()). - Save the result to CSV and read it back to confirm it matches.
Key takeaways
read_csv,read_excel,read_jsonandread_sqlbring data into pandas.- APIs return JSON; always check status codes, limits and licenses.
- Document where each dataset came from.
Practice exercises
- Find one open dataset about Rwanda (for example from NISR or the World Bank) and load it into pandas.
- Write a SQL query with
WHERE,GROUP BYandORDER BYon a small table you create. - Explain the difference between CSV and JSON and when you would use each.
Session 5: Data Cleaning
Learning objectives
- Detect and handle missing values.
- Remove duplicates and fix data types.
- Identify and treat outliers.
- Scale and encode features for later modeling.
Theory: why cleaning matters
“Garbage in, garbage out” is the first law of data work. Real data contains mistakes: typing errors, missing entries, inconsistent spellings and impossible values. A model trained on messy data will learn the mess. A good cleaning process is systematic and documented, so another person can repeat it.
A messy example dataset
import pandas as pd
import numpy as np
raw = pd.DataFrame({
"patient_id": [1, 2, 2, 3, 4, 5, 6],
"district": ["Huye", "huye ", "huye ", "Musanze", "Rubavu", "Gasabo", None],
"age": [34, 29, 29, np.nan, 41, 230, 52],
"visit_date": ["2026-01-05", "2026/01/07", "2026/01/07", "2026-02-10",
"not recorded", "2026-02-12", "2026-02-14"],
"temp_c": [36.8, 37.2, 37.2, 38.5, np.nan, 36.5, 39.1],
})
print(raw)
Step 1: Inspect
raw.info()
print(raw.isna().sum()) # missing values per column
print(raw.duplicated().sum()) # number of duplicate rows
print(raw.describe()) # age max of 230 looks wrong
Step 2: Fix text problems
df = raw.copy() # keep the raw data untouched
df["district"] = df["district"].str.strip().str.title()
strip() removes extra spaces and title()
makes capitalization consistent, so “huye” and “Huye” become the same
value.
Step 3: Remove duplicates
df = df.drop_duplicates()
# or based on a key:
df = df.drop_duplicates(subset="patient_id", keep="first")
Step 4: Fix data types and dates
df["visit_date"] = pd.to_datetime(df["visit_date"], errors="coerce")
# "errors='coerce'" turns values that cannot be parsed into NaT (missing date)
df["age"] = pd.to_numeric(df["age"], errors="coerce")
Step 5: Handle missing values
There are three main options. The right choice depends on the data and the question.
| Strategy | How | When it is reasonable |
|---|---|---|
| Delete rows or columns | dropna() |
Few values are missing and missingness is random |
| Fill with a statistic | fillna(median) |
Numeric columns with modest missingness |
| Fill with a category | fillna("Unknown") |
Categorical data where “unknown” has meaning |
| Model-based filling | Imputers such as KNN | Many missing values with strong relationships |
df["district"] = df["district"].fillna("Unknown")
df["temp_c"] = df["temp_c"].fillna(df["temp_c"].median())
df = df.dropna(subset=["visit_date"]) # a record without a date is unusable
Always ask why values are missing. If sicker patients are less likely to have a temperature recorded, filling with the median may hide a real pattern.
Step 6: Outliers
An outlier is a value far from the rest. It may be an error (age 230) or a real extreme (a very large transaction). Never delete outliers automatically; investigate first.
The IQR rule flags values outside 1.5 times the interquartile range:
q1 = df["age"].quantile(0.25)
q3 = df["age"].quantile(0.75)
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = df[(df["age"] < low) | (df["age"] > high)]
print(outliers)
# Rule for impossible values: age must be between 0 and 120
df.loc[(df["age"] < 0) | (df["age"] > 120), "age"] = np.nan
df["age"] = df["age"].fillna(df["age"].median())
Other approaches are the z-score (distance from the mean in standard deviations) and capping (winsorizing) extreme values.
Step 7: Scale and encode (preparing for ML)
Many algorithms work better when numeric features have similar ranges, and they need numbers instead of text.
from sklearn.preprocessing import MinMaxScaler, StandardScaler
df["age_scaled"] = StandardScaler().fit_transform(df[["age"]]) # mean 0, std 1
df["temp_01"] = MinMaxScaler().fit_transform(df[["temp_c"]]) # range 0 to 1
# one-hot encoding turns categories into 0/1 columns
encoded = pd.get_dummies(df, columns=["district"], drop_first=True)
print(encoded.head())
A reusable cleaning function
def clean_patients(raw):
df = raw.copy()
df["district"] = df["district"].str.strip().str.title().fillna("Unknown")
df["visit_date"] = pd.to_datetime(df["visit_date"], errors="coerce")
df["age"] = pd.to_numeric(df["age"], errors="coerce")
df.loc[(df["age"] < 0) | (df["age"] > 120), "age"] = np.nan
df["age"] = df["age"].fillna(df["age"].median())
df["temp_c"] = df["temp_c"].fillna(df["temp_c"].median())
df = df.drop_duplicates(subset="patient_id").dropna(subset=["visit_date"])
return df
clean = clean_patients(raw)
print(clean)
Case study (health): cleaning a facility dataset
Imagine a monthly report from health facilities in several districts. Common problems you should expect:
- Facility names spelled in different ways across months.
- Zero versus blank: does blank mean “no cases” or “not reported”?
- Totals that do not equal the sum of their parts.
- Dates entered in different formats.
A good data scientist writes a short data quality report: how many rows, how many missing values per column, how many duplicates, which rules were applied and how many records each rule changed. Use only public or anonymized data for practice, and never share personal health information.
Weekly quiz topics
The Friday quiz covers: the data science lifecycle, Python
collections, the difference between loc and
iloc, merge types, missing value strategies and the IQR
rule.
Key takeaways
- Cleaning is a systematic, documented process: inspect, fix text, remove duplicates, fix types, handle missing values, treat outliers, scale and encode.
- Keep the raw data unchanged; wrap your steps in a function.
- Investigate before deleting; missing values and outliers can carry information.
Practice exercises
- Apply the cleaning steps to a messy CSV you create yourself with at least five different problems.
- Compare the mean of a column before and after filling missing values with the median. What changed?
- Write a short data quality report (five lines) for the sample dataset.
Practical Workshop 1: Clean and Profile a Health-Facility Dataset
Time: 90 to 120 minutes. Work: individually or in pairs. Tools: Google Colab, pandas, matplotlib.
Scenario
You are a data analyst at a district health office. A colleague sends you a file of 415 clinic visit records collected from six districts. Before anyone can analyze the data, you must find the problems, fix them, and document what you did. The data below is simulated; it contains the kinds of errors found in real facility data.
Step 0: Generate the messy dataset
Run this cell once. It creates a DataFrame called df
with deliberate problems.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(2026)
n = 400
districts = ["Gasabo", "Huye", "Musanze", "Rubavu", "Nyagatare", "Kayonza"]
df = pd.DataFrame({
"record_id": np.arange(1, n + 1),
"district": rng.choice(districts, n),
"visit_date": pd.to_datetime("2026-01-01")
+ pd.to_timedelta(rng.integers(0, 120, n), unit="D"),
"age": rng.integers(1, 80, n).astype(float),
"temp_c": rng.normal(37.4, 0.9, n).round(1),
"cases": rng.poisson(6, n).astype(float),
})
# inject problems
df["district"] = df["district"].astype(object)
idx = rng.choice(n, 60, replace=False)
df.loc[idx[:20], "district"] = df.loc[idx[:20], "district"].str.lower()
df.loc[idx[20:40], "district"] = " " + df.loc[idx[20:40], "district"] + " "
df.loc[rng.choice(n, 25, replace=False), "age"] = np.nan
df.loc[rng.choice(n, 30, replace=False), "temp_c"] = np.nan
df.loc[rng.choice(n, 20, replace=False), "cases"] = np.nan
df.loc[[10, 87, 203], "age"] = [230, 199, -4]
df.loc[[15, 140], "temp_c"] = [3.6, 98.6]
df["visit_date"] = df["visit_date"].dt.strftime("%Y-%m-%d")
alt = rng.choice(n, 40, replace=False)
df.loc[alt, "visit_date"] = pd.to_datetime(
df.loc[alt, "visit_date"]).dt.strftime("%d/%m/%Y")
df.loc[rng.choice(n, 8, replace=False), "visit_date"] = "not recorded"
df = pd.concat([df, df.sample(15, random_state=1)], ignore_index=True)
raw = df.copy() # keep the raw data untouched
Step 1: Profile the data
Complete the table by running the code and recording what you find.
print(df.shape)
df.info()
print(df.isna().sum())
print("Duplicate rows:", df.duplicated().sum())
print(df["district"].value_counts())
print(df.describe())
| Check | Expected finding | Your result |
|---|---|---|
| Number of rows and columns | 415 rows, 6 columns | |
Missing age / temp_c /
cases |
25 / 31 / 20 | |
| Duplicate rows | 15 | |
Different spellings in district |
18 (there should be only 6 districts) | |
Dates that do not match YYYY-MM-DD |
48 (40 written as DD/MM/YYYY, 8 “not recorded”) |
|
| Impossible ages (below 0 or above 120) | 3 | |
| Impossible temperatures (below 30 or above 43) | 2 |
Step 2: Visualize the problems
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
df.isna().sum().plot.bar(ax=axes[0], color="#c47828", title="Missing values")
df["age"].plot.box(ax=axes[1], title="Age (look for outliers)")
df["temp_c"].plot.box(ax=axes[2], title="Temperature (look for outliers)")
plt.tight_layout(); plt.show()
Question: which column has the most missing values, and which two columns have impossible values?
Step 3: Clean in a function
Write a function clean_visits(raw) that performs the
steps below. Hints are given in the table.
| Task | Hint |
|---|---|
| Remove exact duplicate rows | drop_duplicates() |
| Standardize district names | .str.strip().str.title() |
| Parse both date formats | Try
pd.to_datetime(..., format="%Y-%m-%d", errors="coerce"),
then fill the failures using format="%d/%m/%Y" |
| Set impossible ages to missing | Age must be between 0 and 120 |
| Set impossible temperatures to missing | Body temperature between 30 and 43 degrees |
| Fill missing numeric values | Use the median within each district
(groupby(...).transform("median")) |
| Drop rows without a valid date | dropna(subset=["visit_date"]) |
A possible solution (try it yourself first):
def clean_visits(raw):
df = raw.copy().drop_duplicates()
df["district"] = df["district"].str.strip().str.title()
d1 = pd.to_datetime(df["visit_date"], format="%Y-%m-%d", errors="coerce")
d2 = pd.to_datetime(df["visit_date"], format="%d/%m/%Y", errors="coerce")
df["visit_date"] = d1.fillna(d2)
df.loc[(df["age"] < 0) | (df["age"] > 120), "age"] = np.nan
df.loc[(df["temp_c"] < 30) | (df["temp_c"] > 43), "temp_c"] = np.nan
for col in ["age", "temp_c", "cases"]:
df[col] = df[col].fillna(df.groupby("district")[col].transform("median"))
return df.dropna(subset=["visit_date"]).reset_index(drop=True)
clean = clean_visits(raw)
print(clean.shape, clean["district"].nunique())
print(clean.isna().sum())
You should end with 392 rows (400 after removing duplicates, minus 8 records with no valid date) and exactly 6 districts.
Step 4: Before and after report
Fill in this data quality report for your manager.
| Measure | Before | After |
|---|---|---|
| Rows | 415 | |
| Duplicate rows | 15 | |
| District spellings | 18 | |
Missing values in age, temp_c,
cases |
76 in total | |
| Impossible values | 5 | |
| Valid dates |
Step 5: Compare distributions
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5), sharey=True)
raw["age"].plot.hist(ax=axes[0], bins=30, title="Age: before cleaning")
clean["age"].plot.hist(ax=axes[1], bins=30, title="Age: after cleaning")
plt.tight_layout(); plt.show()
Step 6: A first look at the clean data
clean["month"] = clean["visit_date"].dt.to_period("M")
monthly = clean.groupby(["month", "district"])["cases"].sum().unstack()
monthly.plot(figsize=(8, 4), marker="o", title="Monthly cases by district")
plt.ylabel("Cases"); plt.show()
Deliverables
- A Colab notebook that runs from top to bottom.
- The completed tables from Steps 1 and 4.
- Three sentences explaining why you chose the median to fill missing values.
- One chart saved as a PNG.
Marking guide
| Criterion | Points |
|---|---|
| All problems found and counted | 20 |
| Cleaning function works and is documented | 30 |
| Correct final shape and district count | 15 |
| Data quality report completed | 15 |
| Clear charts with titles and labels | 10 |
| Explanation of choices | 10 |
| Total | 100 |
Extension tasks
- Add a column
age_group(child, adult, older adult) usingpd.cut. - Count how many missing values you filled in each column and report it.
- Write a unit test using
assertthat checks the cleaned data has no missing values and only valid ages.
Week 2: Statistics and Visualization
Goal of the week: extract and communicate insight from data using statistics and visual analytics. By Friday you will have analyzed a dataset, drawn clear charts, built a dashboard and presented your findings.
Session 1: Descriptive Statistics
Learning objectives
- Compute and interpret measures of central tendency, spread and shape.
- Describe the relationship between two variables using correlation.
- Choose the right summary for the type of data.
Theory: types of data
Choosing the right method starts with knowing your data type.
| Type | Meaning | Examples | Suitable summaries |
|---|---|---|---|
| Nominal | Categories without order | District, gender, crop type | Counts, mode, proportions |
| Ordinal | Ordered categories | Education level, satisfaction rating | Median, counts |
| Discrete numeric | Counts | Number of children, visits | Mean, median, range |
| Continuous numeric | Measured values | Height, rainfall, income | Mean, standard deviation, quantiles |
Measures of central tendency
- Mean: the sum of values divided by their number. Sensitive to extreme values.
- Median: the middle value when sorted. Robust to extreme values.
- Mode: the most frequent value.
Imagine five households with monthly incomes (in thousands of RWF): 80, 90, 100, 110, 1,500. The mean is 376, but the median is 100. The median describes a typical household better because one very high income pulls the mean upward. This is why income and house prices are usually reported with the median.
Measures of spread
- Range: maximum minus minimum.
- Variance and standard deviation: how far values typically are from the mean. The standard deviation uses the same units as the data.
- Quartiles and IQR: Q1 is the 25th percentile, Q3 the 75th. IQR = Q3 minus Q1, the spread of the middle half of the data.
- Coefficient of variation: standard deviation divided by mean, useful for comparing spread across variables with different units.
For a sample, the standard deviation is
We divide by (not ) when working with a sample, because a sample tends to underestimate the spread of the full population.
Shape of a distribution
- Skewness: a distribution with a long tail to the right is right-skewed (income is a classic example). Here the mean is greater than the median.
- Kurtosis: how heavy the tails are, meaning how many extreme values exist.
- Modality: one peak (unimodal) or several peaks (multimodal). Several peaks often mean there are mixed groups in the data.
Correlation
Correlation measures how strongly two numeric variables move together. The Pearson correlation coefficient ranges from to .
| r | Interpretation |
|---|---|
| Near +1 | Strong positive relationship |
| Near 0 | No linear relationship |
| Near -1 | Strong negative relationship |
Correlation is not causation. Ice cream sales and drowning incidents both rise in hot months, but ice cream does not cause drowning. A hidden third factor (hot weather) explains both. Pearson’s also measures only linear relationships, so always draw a scatter plot as well.
Hands-on lab
import pandas as pd
import numpy as np
np.random.seed(42)
n = 200
df = pd.DataFrame({
"district": np.random.choice(["Huye", "Musanze", "Rubavu", "Nyagatare"], n),
"rainfall_mm": np.random.normal(1100, 200, n).round(0),
"fertilizer_kg": np.random.normal(60, 15, n).round(1),
})
# make yield depend on rainfall and fertilizer, plus random noise
df["yield_t"] = (0.002 * df["rainfall_mm"] + 0.03 * df["fertilizer_kg"]
+ np.random.normal(0, 0.4, n)).round(2)
print(df.describe())
print("Median yield:", df["yield_t"].median())
print("Skewness:", df["yield_t"].skew())
# correlation matrix
print(df[["rainfall_mm", "fertilizer_kg", "yield_t"]].corr())
# summary per group
print(df.groupby("district")["yield_t"].agg(["mean", "median", "std", "count"]))
(This is simulated data for practice, not real agricultural statistics.)
Interpret the output: which variable is most strongly correlated with yield? Does any district stand out?
Key takeaways
- Choose summaries by data type. Use the median for skewed data.
- Standard deviation and IQR describe spread; skewness describes shape.
- Correlation shows linear association, never proof of cause.
Practice exercises
- Calculate the mean, median and standard deviation of: 12, 15, 11, 14, 90. Explain which measure is misleading and why.
- Create two variables with a strong positive correlation and compute . Then create two with a curved relationship and see what says.
- Explain in two sentences why the mean income of a country can mislead.
Session 2: Probability, Distributions and Hypothesis Testing
Learning objectives
- Explain probability, conditional probability and independence.
- Recognize common distributions (normal, binomial, Poisson).
- Understand sampling and the idea of a confidence interval.
- Carry out and interpret a simple hypothesis test.
Theory: probability basics
Probability measures how likely an event is, between 0 (impossible) and 1 (certain).
- Complement:
- Addition rule (either event):
- Independent events:
- Conditional probability:
Example. Suppose 2% of mobile money transactions are fraudulent. A fraud detector flags 90% of real fraud, and also wrongly flags 5% of normal transactions. If a transaction is flagged, what is the chance it is really fraud? Out of 10,000 transactions, 200 are fraud and 9,800 are normal. The detector flags fraud cases and normal ones. So of 670 flagged transactions, only are real fraud. When an event is rare, even a good detector produces many false alarms. This idea (Bayes’ theorem) is central to evaluating ML models later.
Common distributions
| Distribution | Used for | Example |
|---|---|---|
| Normal | Measurements that cluster around an average | Heights, test scores, measurement error |
| Binomial | Number of successes in a fixed number of trials | Number of patients out of 20 who respond to treatment |
| Poisson | Count of events in a fixed time or area | Number of calls arriving at a help line per hour |
| Uniform | All outcomes equally likely | A fair random number generator |
For a normal distribution, about 68% of values lie within 1 standard deviation of the mean, 95% within 2, and 99.7% within 3.
Sampling and the central limit theorem
We usually study a sample and want to learn about a population. A good sample is random and representative. A biased sample (for example, surveying only people with smartphones) gives misleading results.
The central limit theorem says that the means of many random samples follow an approximately normal distribution, even when the original data is not normal, as long as the samples are large enough. This is why the normal distribution appears so often in statistics.
Confidence intervals
A 95% confidence interval is a range computed from sample data in such a way that, if we repeated the study many times, about 95% of the intervals would contain the true population value. It expresses uncertainty about an estimate. A wide interval means the estimate is uncertain.
Hypothesis testing
A hypothesis test asks whether an observed difference is likely to be due to chance.
- Null hypothesis (): there is no effect or no difference.
- Alternative hypothesis (): there is an effect or difference.
- Choose a significance level (commonly 0.05).
- Compute a test statistic and its p-value: the probability of seeing a result at least this extreme if were true.
- If , we reject ; otherwise we do not reject it.
Important: a p-value is not the probability that the hypothesis is true. A small p-value does not mean the effect is large or important, and “not significant” does not prove there is no effect. Always report the size of the effect along with the p-value.
Which statistical test?
| Question | Data | Typical test | Python |
|---|---|---|---|
| Is a group mean different from a known value? | One numeric variable | One-sample t-test | stats.ttest_1samp |
| Do two groups differ in average? | Numeric outcome, two groups | Two-sample t-test (Welch) | stats.ttest_ind(a, b, equal_var=False) |
| Did the same people change between two times? | Paired numeric values | Paired t-test | stats.ttest_rel |
| Do three or more groups differ in average? | Numeric outcome, several groups | One-way ANOVA | stats.f_oneway |
| Are two categories related? | Two categorical variables | Chi-square test | stats.chi2_contingency |
| Are two numeric variables related? | Two numeric variables | Correlation test | stats.pearsonr, stats.spearmanr |
| Data far from normal or very small sample | Numeric, two groups | Mann-Whitney U test | stats.mannwhitneyu |
Hands-on lab
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
# Normal distribution probabilities
print("P(X < 1.0) =", stats.norm.cdf(1.0)) # about 0.841
print("95th percentile:", stats.norm.ppf(0.95))
# Simulate a binomial experiment: 20 patients, 60% respond
responses = rng.binomial(n=20, p=0.6, size=1000)
print("Average responders:", responses.mean())
# Central limit theorem demo with a skewed distribution
skewed = rng.exponential(scale=2, size=100000)
sample_means = [rng.choice(skewed, 50).mean() for _ in range(2000)]
print("Mean of sample means:", np.mean(sample_means))
# Two-sample t-test: do two farming methods give different yields?
method_a = rng.normal(2.8, 0.5, 30)
method_b = rng.normal(3.1, 0.5, 30)
t_stat, p_value = stats.ttest_ind(method_a, method_b)
print(f"t = {t_stat:.2f}, p = {p_value:.4f}")
# 95% confidence interval for the mean of method_b
ci = stats.t.interval(0.95, df=len(method_b)-1,
loc=method_b.mean(), scale=stats.sem(method_b))
print("95% CI:", ci)
Run the t-test several times with different seeds and sample sizes. Notice how a larger sample makes small differences easier to detect.
Key takeaways
- Conditional probability and base rates explain why rare events cause many false alarms.
- Normal, binomial and Poisson distributions cover many practical problems.
- A p-value measures surprise under ; it is not the probability that is true.
- Always report effect size and confidence intervals.
Practice exercises
- A test is 95% accurate for a disease that affects 1% of people. Estimate the chance that a positive result is correct (use 10,000 people as in the example).
- Use
stats.poissonto find the probability of receiving at least 10 calls in an hour when the average is 6. - Run a t-test comparing two groups from your own simulated data and explain the result in plain language.
Session 3: Exploratory Data Analysis (EDA)
Learning objectives
- Follow a systematic EDA workflow.
- Examine single variables, pairs of variables and groups.
- Spot data quality issues and form hypotheses.
Theory: what is EDA?
Exploratory data analysis is the process of examining data to understand its structure, find patterns and anomalies, test assumptions and decide what to do next. The statistician John Tukey popularized the idea that you should look at data before you model it. Models built without EDA often fail for reasons that a simple chart would have revealed.
A systematic EDA workflow
- Understand the question and context. What do the columns mean? Who collected the data?
- Check structure and quality. Shape, types, missing values, duplicates.
- Univariate analysis. Look at each variable on its own.
- Bivariate analysis. Look at relationships between pairs.
- Multivariate analysis. Look at groups and interactions.
- Record findings and questions. Write what you learn as you go.
Univariate analysis
- Numeric: histogram, box plot, summary statistics.
- Categorical: counts and bar charts.
Bivariate analysis
| Pair | Useful tools |
|---|---|
| Numeric and numeric | Scatter plot, correlation |
| Categorical and numeric | Box plot or violin plot by group, group means |
| Categorical and categorical | Cross-tabulation, stacked bar chart |
Hands-on lab: EDA on a sample dataset
We use the simulated agriculture dataset from Session 1 and add some realism by including a few missing values.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(0)
n = 300
df = pd.DataFrame({
"district": np.random.choice(["Huye", "Musanze", "Rubavu", "Nyagatare", "Kayonza"], n),
"season": np.random.choice(["A", "B"], n),
"rainfall_mm": np.random.normal(1000, 220, n).round(0),
"fertilizer_kg": np.random.normal(55, 18, n).round(1),
})
df["yield_t"] = (0.0018 * df["rainfall_mm"] + 0.028 * df["fertilizer_kg"]
+ np.where(df["season"] == "A", 0.3, 0)
+ np.random.normal(0, 0.4, n)).round(2)
df.loc[np.random.choice(n, 15, replace=False), "fertilizer_kg"] = np.nan
# Step 1: structure and quality
df.info()
print(df.isna().sum())
print(df.duplicated().sum())
# Step 2: univariate
print(df["district"].value_counts())
df["yield_t"].hist(bins=20)
plt.title("Distribution of yield"); plt.xlabel("tonnes per hectare"); plt.show()
# Step 3: bivariate
sns.scatterplot(data=df, x="rainfall_mm", y="yield_t", hue="season")
plt.show()
sns.boxplot(data=df, x="district", y="yield_t")
plt.show()
print(pd.crosstab(df["district"], df["season"]))
# Step 4: multivariate
sns.heatmap(df.select_dtypes("number").corr(), annot=True, cmap="Greens")
plt.show()
sns.pairplot(df[["rainfall_mm", "fertilizer_kg", "yield_t", "season"]], hue="season")
plt.show()
What to look for
- Shape: is each variable symmetric or skewed? Does it need a transformation (such as a logarithm)?
- Outliers: are they errors or real extremes?
- Missing patterns: do missing values concentrate in one district or season?
- Relationships: which variables move together? Is the relationship straight or curved?
- Groups: do some groups behave differently from others?
Common pitfalls
- Simpson’s paradox: a trend that appears in the combined data can reverse inside each group. Always check groups.
- Overfitting to noise: with many charts, some random patterns will look meaningful. Treat findings as hypotheses.
- Ignoring context: a column named “score” means little until you know how it was measured.
Key takeaways
- EDA is a structured conversation with the data: structure, single variables, pairs, groups.
- Charts reveal what summary statistics hide.
- Write down findings and open questions as you go.
Practice exercises
- Perform a complete EDA on a dataset of your choice and write five findings.
- Find one variable that needs a log transformation and show the before and after histograms.
- Check whether missing fertilizer values are related to district.
Session 4: Data Visualization with Matplotlib and Seaborn
Learning objectives
- Choose the right chart for a question.
- Create and customize charts with Matplotlib and Seaborn.
- Apply principles of clear, honest visual communication.
Theory: choosing a chart
Start with the question, then choose the chart.
| Question | Chart |
|---|---|
| How is one numeric variable distributed? | Histogram, box plot, density plot |
| How do categories compare? | Bar chart (sorted) |
| How does a value change over time? | Line chart |
| How are two numeric variables related? | Scatter plot |
| What is the composition of a whole? | Stacked bar, or pie chart for very few parts |
| How do many variables correlate? | Heatmap |
| Where does something happen? | Map |
Principles of effective charts
- One message per chart. The title should state the message, for example “Yields rise with rainfall up to about 1,200 mm”.
- Label everything. Axis titles with units, a legend if there is more than one series, and a source note.
- Start bar charts at zero. Cutting the axis exaggerates differences and misleads the reader.
- Use color with purpose. Highlight what matters and keep the rest quiet. Use color-blind-safe palettes and do not rely on color alone.
- Remove clutter. Fewer gridlines, no 3D effects, no unnecessary decoration.
- Sort categories by value unless they have a natural order.
- Avoid pie charts with many slices; a sorted bar chart is easier to read.
Matplotlib basics
Matplotlib is the foundation library. A figure contains one or more axes (plots).
import matplotlib.pyplot as plt
import numpy as np
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 135, 150, 145, 170, 190]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(months, sales, marker="o", color="#0b563c", linewidth=2)
ax.set_title("Monthly sales grew steadily in the first half of the year")
ax.set_xlabel("Month")
ax.set_ylabel("Sales (thousand RWF)")
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.savefig("sales.png", dpi=200) # save for reports
plt.show()
Several charts together:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(np.random.normal(50, 10, 500), bins=20, color="#4c8a6e")
axes[0].set_title("Histogram")
axes[1].bar(["A", "B", "C"], [30, 45, 25], color="#c47828")
axes[1].set_title("Bar chart")
plt.tight_layout()
plt.show()
Seaborn: statistical charts made simple
Seaborn is built on Matplotlib and works directly with DataFrames.
import seaborn as sns
import pandas as pd
sns.set_theme(style="whitegrid", palette="viridis")
# df: the agriculture dataset from the previous session
sns.histplot(data=df, x="yield_t", kde=True, bins=20) # distribution
sns.boxplot(data=df, x="district", y="yield_t") # groups
sns.violinplot(data=df, x="season", y="yield_t") # shape by group
sns.scatterplot(data=df, x="rainfall_mm", y="yield_t", hue="district")
sns.regplot(data=df, x="rainfall_mm", y="yield_t", scatter_kws={"alpha": 0.4})
sns.barplot(data=df, x="district", y="yield_t", estimator="mean", errorbar="ci")
sns.heatmap(df.select_dtypes("number").corr(), annot=True, cmap="Greens")
sns.pairplot(df, vars=["rainfall_mm", "fertilizer_kg", "yield_t"])
sns.FacetGrid(df, col="district").map(sns.histplot, "yield_t")
plt.show() after each call displays the chart in a
notebook. In older Seaborn versions the errorbar argument
is called ci.
Telling a story with a chart
Compare two versions of the same bar chart. In the first, all bars are the same blue and the title says “Yield by district”. In the second, the best district is dark green, the others are grey, the bars are sorted, and the title says “Nyagatare has the highest average yield”. The second version tells the reader where to look.
avg = df.groupby("district")["yield_t"].mean().sort_values()
colors = ["#0b563c" if d == avg.idxmax() else "#b8c2bd" for d in avg.index]
fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(avg.index, avg.values, color=colors)
ax.set_title(f"{avg.idxmax()} has the highest average yield")
ax.set_xlabel("Average yield (tonnes per hectare)")
for spine in ["top", "right"]:
ax.spines[spine].set_visible(False)
plt.tight_layout()
plt.show()
Hands-on lab
- Create a line chart of a time series (for example monthly rainfall for one place) with a clear title and axis labels.
- Create a sorted, highlighted bar chart of any grouped average.
- Make a three-panel figure: histogram, box plot by group and scatter plot with a trend line.
- Save your best chart as a PNG file.
Key takeaways
- Pick the chart from the question, not from habit.
- Clear titles, labels and highlighted key facts turn charts into stories.
- Do not distort: start bars at zero, avoid 3D, use accessible colors.
Practice exercises
- Take a misleading chart you have seen (for example a truncated axis) and redraw it honestly.
- Show the same data as a pie chart and a sorted bar chart. Which is easier to read?
- Build a small “chart gallery” notebook with one chart per question type in the table above.
Session 5: Dashboards with Power BI or Tableau, and Mini Project Presentations
Learning objectives
- Explain what a dashboard is and design a clear one.
- Build a basic interactive dashboard in Power BI or Tableau.
- Present data findings to a non-technical audience.
Theory: what is a dashboard?
A dashboard is a single screen that shows the most important numbers and charts for a decision, usually with filters so users can explore. A good dashboard answers a defined set of questions for a specific audience. A bad dashboard is a collection of every chart that was possible to make.
Dashboard design principles
- Know the audience and decisions. A district agriculture officer and a national policy maker need different views.
- Put the key numbers first. Show a few KPIs (key performance indicators) at the top, such as total yield, average yield and change from last season.
- Follow a visual hierarchy. The most important chart is top left and largest.
- Keep it simple. Four to six visuals is usually enough.
- Use consistent colors and labels. The same color should always mean the same thing.
- Make filters obvious. Slicers for region, season or date range.
- Check the numbers. A beautiful dashboard with a wrong total destroys trust.
Power BI and Tableau at a glance
| Power BI | Tableau | |
|---|---|---|
| Maker | Microsoft | Salesforce |
| Strengths | Integrates with Excel and Microsoft 365, strong value for money, Power Query for cleaning | Very flexible visuals, strong community and public gallery |
| Free option | Power BI Desktop (Windows) | Tableau Public (published work is public) |
| Language for calculations | DAX | Calculated fields and LOD expressions |
Use whichever tool your instructor provides. The concepts are the same.
Building a dashboard: step by step
- Connect to data. Load your cleaned CSV or Excel
file (export it from pandas with
df.to_csv). - Check the data model. Confirm that data types are correct (numbers, dates, text).
- Create the KPI cards. Total yield, average yield, number of records.
- Add charts. For example: a bar chart of average yield by district, a line chart of yield over seasons, and a scatter plot of rainfall versus yield.
- Add slicers (filters). District and season.
- Format. Title, consistent colors, readable fonts, aligned elements.
- Test. Click each filter and confirm the numbers behave as expected.
- Publish or export. Share as a report link or PDF, following your organization’s data rules.
If you cannot install either tool, you can build a simple interactive view in Python with the Plotly library:
import plotly.express as px
fig = px.scatter(df, x="rainfall_mm", y="yield_t", color="district",
hover_data=["fertilizer_kg"], title="Rainfall and yield by district")
fig.show()
fig2 = px.bar(df.groupby("district", as_index=False)["yield_t"].mean(),
x="district", y="yield_t", title="Average yield by district")
fig2.show()
Mini project
Task: in pairs or small groups, analyze a public dataset and present your findings.
Steps and deliverables
- Choose a dataset and a clear question (for example “How do rainfall and fertilizer affect yield?”).
- Clean the data and document your choices.
- Run an EDA and compute relevant statistics.
- Create three to five clear charts.
- Present in five minutes: question, data, method, three findings, one limitation and one recommendation.
Assessment guide (suggested)
| Criterion | What good work looks like |
|---|---|
| Question | Clear, specific and answerable with the data |
| Data handling | Cleaning documented; sources named |
| Analysis | Appropriate statistics and honest interpretation |
| Visuals | Clear, labeled, support the story |
| Communication | Structured, within time, plain language |
Case study (agriculture): crop analysis and dashboard
A district agriculture office wants to know which factors are linked to yields. A data analyst combines three sources: seasonal yield records, rainfall data from weather stations and fertilizer distribution records. The cleaning step standardizes district names and removes duplicate reports. The analysis shows a positive link between rainfall and yield up to a point, a positive link with fertilizer use, and clear differences between districts. The dashboard gives officers KPI cards for average yield and fertilizer use, a district comparison, and a season filter.
Discussion questions: What decisions could this dashboard support? What important factors are missing (soil, seed type, pests)? Why must we be careful about claiming that fertilizer causes higher yields?
Key takeaways
- A dashboard serves a specific audience and a set of decisions.
- Put the most important information first, keep it simple, and verify numbers.
- A good presentation states the question, the evidence and the limits.
Practice exercises
- Sketch on paper a dashboard for a hospital manager who wants to monitor monthly visits and stock-outs. List the KPIs and filters.
- Rewrite a technical finding such as “the correlation is 0.62 with p < 0.01” for a non-technical audience.
- Prepare a one-slide summary of your mini project.
Practical Workshop 2: Agriculture Analysis and Dashboard
Time: 2 to 3 hours. Work: pairs. Tools: Google Colab, pandas, SciPy, Seaborn, plus Power BI or Tableau (optional).
Scenario
A district agriculture office wants to know what is linked to higher crop yields so it can plan fertilizer support. You receive records of 600 farm plots. The data is simulated for practice and does not describe real farms.
Step 0: Generate the dataset
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
rng = np.random.default_rng(2027)
n = 600
districts = ["Gasabo", "Huye", "Musanze", "Rubavu", "Nyagatare", "Kayonza"]
base = dict(zip(districts, [2.4, 2.8, 3.2, 3.0, 2.6, 2.5]))
df = pd.DataFrame({
"district": rng.choice(districts, n),
"season": rng.choice(["A", "B"], n),
"rainfall_mm": rng.normal(1050, 230, n).round(0).clip(300),
"fertilizer_kg": rng.normal(55, 18, n).round(1).clip(0),
"area_ha": rng.uniform(0.3, 3.0, n).round(2),
})
df["yield_t"] = (df["district"].map(base)
+ 0.0012 * (df["rainfall_mm"] - 1050)
+ 0.012 * (df["fertilizer_kg"] - 55)
+ np.where(df["season"] == "A", 0.25, 0)
+ rng.normal(0, 0.45, n)).round(2).clip(0.2)
df.loc[rng.choice(n, 25, replace=False), "fertilizer_kg"] = np.nan
Part A: Describe the data (30 minutes)
- Show the structure with
info()anddescribe(). - Create a summary table of yield by district, sorted from highest to lowest:
summary = (df.groupby("district")["yield_t"]
.agg(["count", "mean", "median", "std"])
.round(2).sort_values("mean", ascending=False))
print(summary)
- Fill in the answers. Your values should be close to the ones shown.
| Question | Expected answer | Your answer |
|---|---|---|
| Missing values and where? | 25, all in fertilizer_kg |
|
| District with the highest mean yield | Musanze (about 3.37 t/ha) | |
| District with the lowest mean yield | Gasabo (about 2.58 t/ha) | |
| Mean yield in season A and season B | About 3.00 and 2.75 |
Part B: Test relationships (45 minutes)
B1. Correlations
corr = df[["rainfall_mm", "fertilizer_kg", "area_ha", "yield_t"]].corr()
sns.heatmap(corr, annot=True, cmap="Greens", vmin=-1, vmax=1)
plt.title("Correlation matrix"); plt.show()
print(corr["yield_t"].round(2))
Expected: rainfall about 0.44, fertilizer about 0.32, area close to 0.
B2. Season A versus season B
a = df.loc[df["season"] == "A", "yield_t"]
b = df.loc[df["season"] == "B", "yield_t"]
t, p = stats.ttest_ind(a, b, equal_var=False)
print(f"Mean A = {a.mean():.2f}, Mean B = {b.mean():.2f}, t = {t:.2f}, p = {p:.6f}")
ci = stats.t.interval(0.95, len(a) - 1, loc=a.mean() - b.mean(), scale=np.sqrt(a.var()/len(a) + b.var()/len(b)))
print("Approximate 95% CI for the difference:", np.round(ci, 2))
Expected: a t statistic near 4.8 and a very small p-value. Write two sentences interpreting the result in plain language and say how large the difference is in practical terms.
B3. District differences with a one-way ANOVA:
groups = [g["yield_t"].values for _, g in df.groupby("district")]
print(stats.f_oneway(*groups))
Part C: Make charts (45 minutes)
Create these four charts. Each needs a message title, axis labels with units and a readable layout.
| Chart | Question it answers | Code hint |
|---|---|---|
| Sorted horizontal bar of mean yield by district | Which districts perform best? | groupby, sort_values,
barh |
| Box plot of yield by season | How do the seasons differ? | sns.boxplot |
| Scatter of rainfall against yield with a trend line | Does more rain mean more yield? | sns.regplot |
| Heatmap of mean yield by district and season | Where and when is yield highest? | pivot_table then sns.heatmap |
pivot = df.pivot_table(index="district", columns="season", values="yield_t", aggfunc="mean")
sns.heatmap(pivot, annot=True, fmt=".2f", cmap="YlGn")
plt.title("Mean yield (t/ha) by district and season"); plt.show()
Part D: Build the dashboard (45 minutes)
Export your data with
df.to_csv("yields.csv", index=False) and build a dashboard
in Power BI or Tableau using the wireframe in Figure 9 (Week 2, Session
5). Use this checklist:
If you cannot use either tool, build an interactive Plotly version:
import plotly.express as px
fig = px.scatter(df, x="rainfall_mm", y="yield_t", color="district", facet_col="season",
trendline="ols", title="Rainfall and yield by district and season")
fig.show()
Part E: Tell the story (15 minutes)
Complete the findings log, then present it in three minutes to another pair.
| Finding | Evidence (number or chart) | So what? (recommendation) | Limitation |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 |
Careful with cause and effect: this is observational data. Even if fertilizer and yield are correlated, other factors such as soil, seed type and farm management could explain the link. Say what extra data you would need.
Marking guide
| Criterion | Points |
|---|---|
| Correct summary tables | 15 |
| Correct tests and plain-language interpretation | 25 |
| Four clear, honest charts | 25 |
| Dashboard design and accuracy | 20 |
| Story and limitations | 15 |
| Total | 100 |
Extension tasks
- Fill the missing fertilizer values with the district median and check whether conclusions change.
- Fit a simple regression of yield on rainfall and fertilizer using
statsmodelsand interpret the coefficients. - Find the plots with the highest yield given low fertilizer use. What might explain them?
Week 3: Machine Learning
Goal of the week: build, evaluate and improve predictive models. By Friday you will have trained regression, classification, clustering and neural network models and judged them honestly on unseen data.
Session 1: The Machine Learning Workflow and Linear Regression
Learning objectives
- Distinguish supervised, unsupervised and reinforcement learning.
- Explain features, labels, training and testing.
- Build and interpret a linear regression model.
Theory: types of machine learning
| Type | Learns from | Goal | Examples |
|---|---|---|---|
| Supervised | Labeled examples (inputs and correct answers) | Predict a label for new data | House price prediction, spam detection, disease diagnosis |
| Unsupervised | Unlabeled data | Find structure | Customer segments, anomaly detection |
| Reinforcement | Rewards from actions in an environment | Learn a strategy | Game playing, robot control |
Supervised learning has two main tasks. Regression predicts a number (price, yield, temperature). Classification predicts a category (spam or not, which crop disease).
The ML workflow
- Frame the problem. What exactly do you predict, and how will the prediction be used?
- Prepare data. Clean, encode and select features.
- Split the data. Keep a portion hidden to test the model honestly.
- Train the model on the training set.
- Evaluate on the test set with suitable metrics.
- Improve. Try better features, other algorithms, tuning.
- Deploy and monitor.
Terminology: features (X) are the input columns; the target or label (y) is what we predict.
Why we split the data
If you test a model on the same data it learned from, it may look perfect simply because it memorized the data. We therefore split the data into a training set (often 70 to 80%) and a test set (20 to 30%). The test set acts like the future: data the model has never seen. For model selection we also use a validation set or cross-validation, so the test set is used only once at the end.
Linear regression
Linear regression fits a straight line (or plane) to predict a numeric target:
Each coefficient tells us how much the prediction changes when feature increases by one unit, holding the others fixed. The model chooses coefficients that minimize the sum of squared errors between predictions and true values.
Assumptions to check: a roughly linear relationship, errors without strong patterns, no extreme outliers dominating, and features that are not almost copies of each other (multicollinearity).
Regression metrics
| Metric | Meaning |
|---|---|
| MAE (mean absolute error) | Average size of the error, in the units of the target |
| RMSE (root mean squared error) | Like MAE but punishes large errors more |
| R squared | Share of the variation in the target explained by the model (1 is perfect, 0 is no better than predicting the mean) |
Hands-on lab: predicting crop yield
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# Simulated data (for practice only)
rng = np.random.default_rng(7)
n = 500
df = pd.DataFrame({
"rainfall_mm": rng.normal(1050, 200, n),
"fertilizer_kg": rng.normal(55, 15, n),
"area_ha": rng.uniform(0.5, 3, n),
})
df["yield_t"] = (0.002 * df["rainfall_mm"] + 0.03 * df["fertilizer_kg"]
+ 0.1 * df["area_ha"] + rng.normal(0, 0.35, n))
X = df[["rainfall_mm", "fertilizer_kg", "area_ha"]]
y = df["yield_t"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("MAE :", mean_absolute_error(y_test, pred))
print("RMSE:", np.sqrt(mean_squared_error(y_test, pred)))
print("R^2 :", r2_score(y_test, pred))
# interpret coefficients
for name, coef in zip(X.columns, model.coef_):
print(f"{name:15s} {coef: .4f}")
print("Intercept:", model.intercept_)
Plot predicted versus actual values. Points close to the diagonal line mean good predictions.
import matplotlib.pyplot as plt
plt.scatter(y_test, pred, alpha=0.5)
lims = [y_test.min(), y_test.max()]
plt.plot(lims, lims, color="red")
plt.xlabel("Actual yield"); plt.ylabel("Predicted yield")
plt.title("Predicted versus actual"); plt.show()
A residual plot (errors against predictions) should show random scatter. A curve or funnel shape tells you the model is missing something.
Key takeaways
- Supervised learning uses labeled data; regression predicts numbers and classification predicts categories.
- Always evaluate on data the model has not seen.
- Coefficients give interpretable effects; check the assumptions and plot the residuals.
Practice exercises
- Change
test_sizeto 0.1 and 0.5. How do the metrics change, and why? - Add a useless random feature to the data. Does R squared on the test set improve?
- Explain MAE and RMSE to a farmer in plain language.
Session 2: Classification and Model Evaluation
Learning objectives
- Build a logistic regression classifier.
- Interpret a confusion matrix.
- Compute and choose among accuracy, precision, recall, F1 and ROC AUC.
Theory: logistic regression
Despite its name, logistic regression is a classification method. It computes a score from the features and converts it to a probability between 0 and 1 with the logistic (sigmoid) function:
A threshold (often 0.5) turns the probability into a class. Moving the threshold trades one kind of error for another.
The confusion matrix
For a yes or no problem, every prediction falls in one of four boxes.
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
Classification metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | How often is the model right overall? |
| Precision | TP / (TP + FP) | When it says positive, how often is it right? |
| Recall (sensitivity) | TP / (TP + FN) | Of all real positives, how many did it find? |
| F1 score | 2 × (Precision × Recall) / (Precision + Recall) | Balance of precision and recall |
| ROC AUC | Area under the ROC curve | How well the model ranks positives above negatives across all thresholds |
Accuracy can mislead. If only 1% of transactions are fraud, a model that always says “not fraud” has 99% accuracy and catches no fraud. For imbalanced problems, use precision, recall, F1 and AUC.
Which metric matters? It depends on the cost of each mistake.
- Cancer screening: a missed case (false negative) is costly, so aim for high recall.
- Blocking a customer’s account for suspected fraud: wrongly blocking customers (false positives) has a cost, so precision matters too.
Hands-on lab: predicting loan default (simulated data)
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import (confusion_matrix, classification_report,
roc_auc_score, RocCurveDisplay)
rng = np.random.default_rng(3)
n = 2000
df = pd.DataFrame({
"income_k": rng.normal(250, 90, n).clip(30), # thousand RWF per month
"loan_k": rng.normal(400, 150, n).clip(50),
"late_payments": rng.poisson(1.2, n),
})
risk = (-2.2 + 0.006 * df["loan_k"] - 0.007 * df["income_k"]
+ 0.55 * df["late_payments"])
p = 1 / (1 + np.exp(-risk))
df["default"] = rng.binomial(1, p)
print(df["default"].mean()) # share of defaults
X = df[["income_k", "loan_k", "late_payments"]]
y = df["default"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
clf = make_pipeline(StandardScaler(), LogisticRegression())
clf.fit(X_train, y_train)
pred = clf.predict(X_test)
proba = clf.predict_proba(X_test)[:, 1]
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred))
print("ROC AUC:", roc_auc_score(y_test, proba))
RocCurveDisplay.from_predictions(y_test, proba)
stratify=y keeps the same proportion of defaults in the
training and test sets. A pipeline keeps the scaler and
the model together, so the scaler learns only from the training data.
This avoids data leakage, which happens when
information from the test set sneaks into training and makes results
look better than they will be in real use.
Trying a different threshold
for threshold in [0.2, 0.3, 0.5]:
pred_t = (proba >= threshold).astype(int)
print(threshold)
print(classification_report(y_test, pred_t, digits=3))
A lower threshold catches more defaulters (higher recall) but also wrongly flags more good customers (lower precision). A lender chooses the threshold using the real cost of each error.
Key takeaways
- Logistic regression predicts probabilities; the threshold sets the class.
- The confusion matrix underlies precision, recall and F1.
- Accuracy alone is dangerous with imbalanced data.
- Use pipelines to prevent data leakage.
Practice exercises
- Compute precision and recall by hand from a confusion matrix with TP=40, FP=10, FN=20, TN=130.
- Change the model so that defaults are rarer (about 2%) and observe what happens to accuracy versus recall.
- Write one sentence about which metric you would prioritize for a malaria test, and why.
Session 3: Decision Trees, Random Forests, Overfitting and Tuning
Learning objectives
- Explain how decision trees and random forests make predictions.
- Recognize overfitting and underfitting.
- Use cross-validation and hyperparameter tuning.
Theory: decision trees
A decision tree asks a series of yes or no questions about the features until it reaches a prediction, like a flowchart. For example: Is income below 150? If yes, are there more than 2 late payments? … At each step the tree picks the question that best separates the classes, measured by a purity score such as Gini impurity or entropy.
Advantages: easy to explain, works with numbers and categories, needs little scaling. Disadvantage: a deep tree memorizes the training data and performs poorly on new data.
Overfitting and underfitting
| Underfitting | Good fit | Overfitting | |
|---|---|---|---|
| Model complexity | Too simple | Right | Too complex |
| Training performance | Poor | Good | Excellent |
| Test performance | Poor | Good | Much worse than training |
| Typical fix | More features, more complex model | Keep | Simplify, more data, regularize, ensembles |
The central challenge of ML is generalization: performing well on new data. A large gap between training and test performance signals overfitting.
The bias-variance trade-off summarizes this: simple models have high bias (they miss real patterns), complex models have high variance (they chase noise). The goal is the balance point.
Random forests and ensembles
An ensemble combines many models to get a better one. A random forest trains many decision trees, each on a random sample of the rows and a random subset of the features, and combines them by voting (classification) or averaging (regression). Individual trees overfit in different ways, and averaging cancels much of the noise. Random forests are strong general-purpose models and need little tuning.
Gradient boosting (for example XGBoost, LightGBM) builds trees one after another, each correcting the errors of the previous ones. It often wins on tabular data but needs more careful tuning.
Cross-validation
Instead of one train and test split, k-fold cross-validation splits the training data into k parts (often 5). It trains on k-1 parts and validates on the remaining part, rotating until every part has been used once. The average score is a more reliable estimate and less dependent on luck in the split.
Hyperparameters and tuning
Parameters are learned from data (such as regression coefficients). Hyperparameters are settings chosen by you before training (such as the maximum depth of a tree or the number of trees). Grid search tries every combination from a list; random search samples combinations and is often more efficient.
Comparing the main algorithms
| Algorithm | Strengths | Weaknesses | Needs scaling? |
|---|---|---|---|
| Linear and logistic regression | Fast, interpretable coefficients, good baseline | Misses curved or complex relationships | Yes (for logistic with regularization) |
| Decision tree | Easy to explain and draw, handles mixed data | Overfits easily, unstable | No |
| Random forest | Strong accuracy, robust to noise, little tuning | Harder to interpret, larger models | No |
| Gradient boosting | Often the best on tabular data | More tuning, can overfit | No |
| k-nearest neighbors | Simple idea, no training step | Slow on big data, sensitive to scale | Yes |
| Neural network | Excellent for images, text, audio, large data | Needs much data and tuning, hard to explain | Yes |
Hands-on lab
Continue with the loan data (X_train,
X_test, y_train, y_test) from
Session 2.
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.metrics import f1_score, roc_auc_score
import matplotlib.pyplot as plt
# 1. An unrestricted tree overfits
deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("Deep tree train F1:", f1_score(y_train, deep.predict(X_train)))
print("Deep tree test F1:", f1_score(y_test, deep.predict(X_test)))
# 2. A shallow tree generalizes better and can be drawn
shallow = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print("Shallow test F1:", f1_score(y_test, shallow.predict(X_test)))
plt.figure(figsize=(12, 5))
plot_tree(shallow, feature_names=X.columns, class_names=["repaid", "default"], filled=True)
plt.show()
# 3. Random forest
rf = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)
rf.fit(X_train, y_train)
print("RF test AUC:", roc_auc_score(y_test, rf.predict_proba(X_test)[:, 1]))
# 4. Cross-validation
scores = cross_val_score(rf, X_train, y_train, cv=5, scoring="roc_auc")
print("CV AUC:", scores.mean(), "+/-", scores.std())
# 5. Hyperparameter tuning
grid = GridSearchCV(
RandomForestClassifier(random_state=0),
param_grid={"n_estimators": [100, 300], "max_depth": [3, 5, 8, None],
"min_samples_leaf": [1, 5, 20]},
cv=5, scoring="roc_auc", n_jobs=-1)
grid.fit(X_train, y_train)
print("Best settings:", grid.best_params_)
print("Best CV AUC :", grid.best_score_)
# 6. Which features matter?
importance = pd.Series(rf.feature_importances_, index=X.columns).sort_values()
importance.plot.barh(); plt.title("Feature importance"); plt.show()
Notice the gap between training and test scores of the unrestricted tree compared with the forest. After tuning, evaluate the final model once on the test set.
Interpreting models
Feature importance shows which inputs the model relies on, but it does not show the direction of the effect and can be misleading when features are correlated. Tools such as permutation importance and SHAP give more reliable explanations. Explanations matter in high-stakes areas such as credit and health, where people have the right to understand decisions that affect them.
Key takeaways
- Trees are interpretable but overfit; forests combine many trees for stable, strong performance.
- A big gap between training and test scores means overfitting.
- Use cross-validation to select models and tune hyperparameters; keep the test set for the final check.
Practice exercises
- Vary
max_depthfrom 1 to 15 for a single tree and plot training and test F1 against depth. Where does overfitting begin? - Compare logistic regression and random forest on the same data. Which wins and by how much?
- Explain overfitting using an analogy from school (for example memorizing past exam answers).
Session 4: Unsupervised Learning: Clustering and Dimensionality Reduction
Learning objectives
- Explain clustering and apply k-means.
- Choose the number of clusters and evaluate results.
- Use PCA to reduce dimensions and visualize data.
Theory: learning without labels
In unsupervised learning there is no correct answer to learn from. The goal is to discover structure: groups of similar items, unusual items, or simpler representations of complex data.
k-means clustering
k-means divides data into k groups.
- Choose k and place k starting centers.
- Assign every point to its nearest center.
- Move each center to the mean of its assigned points.
- Repeat steps 2 and 3 until the centers stop moving.
Limits of k-means: you must choose k; it assumes roughly round, similar-sized clusters; it is sensitive to scale (so always standardize features first) and to outliers. Other methods include hierarchical clustering and DBSCAN, which can find clusters of any shape and mark outliers as noise.
Choosing k
- Elbow method: plot the within-cluster sum of squares (called inertia) against k and look for the “elbow” where improvement slows.
- Silhouette score: from -1 to 1, higher means points are well matched to their own cluster and far from others.
- Business sense: the clusters must be useful and describable. Four segments you can act on beat seven that you cannot explain.
Dimensionality reduction with PCA
Principal component analysis (PCA) finds new axes (principal components) that capture as much of the data’s variation as possible. The first component captures the most, the second the next most, and so on. By keeping only the first few components, we can:
- visualize high-dimensional data in two dimensions,
- remove noise and redundancy,
- speed up other algorithms.
Always standardize features before PCA. Components are mixtures of the original features, so they are harder to interpret than the original columns.
Hands-on lab: segmenting mobile money customers (simulated)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
rng = np.random.default_rng(11)
def group(n, tx, amount, balance, agents):
return pd.DataFrame({
"tx_per_month": rng.poisson(tx, n),
"avg_amount_k": rng.normal(amount, amount * 0.2, n).clip(1),
"avg_balance_k": rng.normal(balance, balance * 0.3, n).clip(0),
"agent_visits": rng.poisson(agents, n),
})
customers = pd.concat([
group(300, 4, 8, 15, 3), # light users
group(300, 25, 20, 60, 1), # frequent small-value users
group(150, 12, 120, 400, 2), # high-value users
], ignore_index=True)
X = StandardScaler().fit_transform(customers)
# choose k
inertia, sil = [], []
ks = range(2, 9)
for k in ks:
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
inertia.append(km.inertia_)
sil.append(silhouette_score(X, km.labels_))
plt.plot(ks, inertia, marker="o"); plt.title("Elbow plot"); plt.show()
print(dict(zip(ks, np.round(sil, 3))))
# final model
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
customers["segment"] = km.labels_
print(customers.groupby("segment").mean().round(1))
print(customers["segment"].value_counts())
# visualize with PCA
pca = PCA(n_components=2)
coords = pca.fit_transform(X)
print("Variance explained:", pca.explained_variance_ratio_)
plt.scatter(coords[:, 0], coords[:, 1], c=customers["segment"], cmap="viridis", alpha=0.6)
plt.xlabel("Component 1"); plt.ylabel("Component 2"); plt.title("Customer segments")
plt.show()
After clustering, profile each segment by looking at group averages and give it a plain name (for example “light users”, “frequent small payers”, “high-value savers”). Then think about how a service provider could use these segments, such as different offers or support, and what privacy rules apply when analyzing customer data.
Anomaly detection
A related task finds unusual points, such as suspicious transactions. A simple method is the Isolation Forest.
from sklearn.ensemble import IsolationForest
iso = IsolationForest(contamination=0.02, random_state=0).fit(X)
customers["anomaly"] = iso.predict(X) == -1
print(customers["anomaly"].sum(), "points flagged for review")
Flagged points are only candidates for review by a human. They are not proof of wrongdoing.
Key takeaways
- Clustering finds groups without labels; k-means is simple but needs scaled data and a chosen k.
- Use the elbow, silhouette score and usefulness to choose k.
- PCA compresses many features into a few components for visualization and noise removal.
Practice exercises
- Run k-means without standardizing the features. How do the clusters change, and why?
- Try hierarchical clustering with
AgglomerativeClusteringand compare it to k-means. - Name and describe each segment from the lab in one sentence.
Session 5: Neural Networks and Deep Learning
Learning objectives
- Explain neurons, layers, activation functions and how a network learns.
- Train a simple neural network on tabular data.
- Describe common deep learning architectures and their uses.
Theory: the artificial neuron
A neuron takes several inputs, multiplies each by a weight, adds them with a bias, and passes the sum through an activation function:
The activation function adds non-linearity, which lets networks learn curved, complex patterns.
| Activation | Where used | Behavior |
|---|---|---|
| ReLU | Hidden layers | Outputs 0 for negative values, the value itself otherwise |
| Sigmoid | Binary output | Squashes values to between 0 and 1 |
| Softmax | Multi-class output | Converts scores to probabilities that add up to 1 |
Layers and learning
A neural network stacks neurons in layers: an input layer, one or more hidden layers and an output layer. A network with many hidden layers is a deep network.
Training works in a loop:
- Forward pass: send inputs through the network to get predictions.
- Loss: measure how wrong the predictions are (for example binary cross-entropy for classification, mean squared error for regression).
- Backpropagation: compute how much each weight contributed to the error.
- Update: adjust the weights a little in the direction that reduces the loss (gradient descent). The step size is the learning rate.
One pass through all training data is an epoch. Data is fed in small groups called batches.
Preventing overfitting in networks
- Early stopping: stop training when validation loss stops improving.
- Dropout: randomly switch off some neurons during training.
- Regularization: penalize very large weights.
- More data and data augmentation (for images: flips, crops).
Common architectures
| Architecture | Good for | Example |
|---|---|---|
| Feed-forward (MLP) | Tabular data | Credit scoring |
| Convolutional (CNN) | Images | Detecting crop disease from leaf photos |
| Recurrent (RNN, LSTM) | Sequences | Time series, speech |
| Transformer | Language and many other data types | Translation, chatbots, large language models |
Deep learning shines on images, audio and text with large datasets. On small tabular data, random forests or gradient boosting often match or beat neural networks with much less effort.
Main neural network settings (hyperparameters)
| Setting | What it controls | If too low | If too high |
|---|---|---|---|
| Learning rate | Size of each weight update | Training is very slow | Training becomes unstable |
| Number of layers and neurons | Model capacity | Underfitting | Overfitting, slow training |
| Epochs | How long to train | Underfitting | Overfitting (use early stopping) |
| Batch size | Examples per update | Noisy, slow | Needs more memory, may generalize less well |
| Dropout rate | Regularization strength | Overfitting | Underfitting |
Hands-on lab: a neural network with Keras
First with scikit-learn’s simple network (no extra installation):
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score
mlp = make_pipeline(
StandardScaler(),
MLPClassifier(hidden_layer_sizes=(32, 16), max_iter=500,
early_stopping=True, random_state=0))
mlp.fit(X_train, y_train)
print("MLP AUC:", roc_auc_score(y_test, mlp.predict_proba(X_test)[:, 1]))
Then with Keras (available in Colab):
import tensorflow as tf
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train)
Xtr, Xte = scaler.transform(X_train), scaler.transform(X_test)
model = keras.Sequential([
keras.layers.Input(shape=(Xtr.shape[1],)),
keras.layers.Dense(32, activation="relu"),
keras.layers.Dropout(0.2),
keras.layers.Dense(16, activation="relu"),
keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy",
metrics=["accuracy", keras.metrics.AUC(name="auc")])
history = model.fit(
Xtr, y_train.values, validation_split=0.2, epochs=50, batch_size=32,
callbacks=[keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True)],
verbose=0)
print(model.evaluate(Xte, y_test.values, verbose=0))
import matplotlib.pyplot as plt
plt.plot(history.history["loss"], label="train")
plt.plot(history.history["val_loss"], label="validation")
plt.legend(); plt.xlabel("epoch"); plt.title("Learning curves"); plt.show()
Read the learning curves: when training loss keeps falling while validation loss rises, the network is overfitting.
Case study (finance and mobile money): fraud detection or credit risk
A mobile money provider wants to detect fraudulent transactions. Fraud is rare (well under 1% of transactions), so the team should:
- use precision, recall and AUC rather than accuracy,
- split data by time (train on the past, test on the future) to mimic real use,
- try logistic regression, random forests and boosting as baselines before neural networks,
- choose the threshold using the cost of missed fraud versus the cost of blocking honest customers,
- send flagged cases to human reviewers and give customers a way to appeal,
- monitor the model, since fraudsters change their behavior.
For credit scoring the same steps apply, with added attention to fairness: the model must not unfairly disadvantage groups of people, and borrowers should be able to understand and contest decisions.
Key takeaways
- Neural networks stack layers of weighted sums and non-linear activations, trained by gradient descent.
- Overfitting is controlled with early stopping, dropout and regularization.
- Choose the architecture for the data type; always compare with simpler baselines.
Practice exercises
- Change the number of neurons and layers in the Keras model. How do the validation results change?
- Remove early stopping and train for 200 epochs. Describe what you see in the learning curves.
- List three differences between how a random forest and a neural network learn.
Practical Workshop 3: Compare Models to Predict Loan Default
Time: 2 to 3 hours. Work: pairs. Tools: Google Colab, scikit-learn, matplotlib.
Scenario
A microfinance institution wants to flag loans that are likely to default so officers can offer support early. You will build and compare several models on simulated data, choose a decision threshold, and check performance for urban and rural borrowers. The data does not describe real people.
Step 0: Generate the dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, roc_auc_score, confusion_matrix)
rng = np.random.default_rng(3)
n = 3000
df = pd.DataFrame({
"income_k": rng.normal(250, 90, n).clip(30),
"loan_k": rng.normal(400, 150, n).clip(50),
"late_payments": rng.poisson(1.2, n),
"urban": rng.integers(0, 2, n),
})
risk = (-2.4 + 0.006 * df["loan_k"] - 0.007 * df["income_k"]
+ 0.55 * df["late_payments"] - 0.2 * df["urban"])
df["default"] = rng.binomial(1, 1 / (1 + np.exp(-risk)))
print("Default rate:", df["default"].mean()) # about 0.27
Step 1: Explore and split
- Show the class balance. About 27% of loans default, so accuracy alone will mislead.
- Plot default rate by number of late payments.
- Split the data with stratification:
X = df[["income_k", "loan_k", "late_payments"]]
y = df["default"]
Xtr, Xte, ytr, yte, gtr, gte = train_test_split(
X, y, df["urban"], test_size=0.25, stratify=y, random_state=42)
Step 2: Train and compare five models
models = {
"Baseline (always repaid)": DummyClassifier(strategy="most_frequent"),
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
"Decision tree (depth 3)": DecisionTreeClassifier(max_depth=3, random_state=0),
"Decision tree (no limit)": DecisionTreeClassifier(random_state=0),
"Random forest": RandomForestClassifier(n_estimators=300, min_samples_leaf=5,
random_state=0, n_jobs=-1),
}
rows = []
for name, m in models.items():
m.fit(Xtr, ytr)
pred = m.predict(Xte)
proba = m.predict_proba(Xte)[:, 1]
rows.append({
"model": name,
"accuracy": accuracy_score(yte, pred),
"precision": precision_score(yte, pred, zero_division=0),
"recall": recall_score(yte, pred),
"f1": f1_score(yte, pred),
"auc": roc_auc_score(yte, proba),
"train_f1": f1_score(ytr, m.predict(Xtr)),
})
results = pd.DataFrame(rows).round(2)
print(results.to_string(index=False))
Typical results (your numbers may differ slightly with other library versions):
| Model | Accuracy | Precision | Recall | F1 | AUC | Train F1 |
|---|---|---|---|---|---|---|
| Baseline (always repaid) | 0.73 | 0.00 | 0.00 | 0.00 | 0.50 | 0.00 |
| Logistic regression | 0.76 | 0.61 | 0.36 | 0.45 | 0.77 | 0.47 |
| Decision tree (depth 3) | 0.76 | 0.75 | 0.16 | 0.27 | 0.73 | 0.31 |
| Decision tree (no limit) | 0.66 | 0.39 | 0.45 | 0.42 | 0.60 | 1.00 |
| Random forest | 0.76 | 0.59 | 0.40 | 0.48 | 0.76 | 0.66 |
Discussion questions
- The baseline has 73% accuracy but catches no defaults. What does this tell you about accuracy?
- The unlimited tree scores a perfect Train F1 of 1.00 but only 0.42 on test data. What is this called?
- Which model would you choose, and why? Consider performance, simplicity and explainability.
Step 3: Choose a threshold
The default threshold of 0.5 catches only a third of defaults. A lender may prefer to catch more and accept more false alarms.
proba = models["Logistic regression"].predict_proba(Xte)[:, 1]
rows = []
for t in [0.2, 0.3, 0.4, 0.5]:
pred = (proba >= t).astype(int)
rows.append({"threshold": t,
"flagged": int(pred.sum()),
"precision": precision_score(yte, pred),
"recall": recall_score(yte, pred)})
print(pd.DataFrame(rows).round(2))
Typical results for the logistic model:
| Threshold | Loans flagged (of 750) | Precision | Recall |
|---|---|---|---|
| 0.2 | 425 | 0.40 | 0.83 |
| 0.3 | 292 | 0.47 | 0.68 |
| 0.4 | 195 | 0.52 | 0.50 |
| 0.5 | 120 | 0.61 | 0.36 |
Cost exercise. Suppose a missed default costs the institution 100,000 RWF and a follow-up visit to a borrower who would have repaid costs 10,000 RWF. Using the confusion matrix at each threshold, compute the total cost and pick the cheapest threshold.
cost_missed, cost_visit = 100_000, 10_000
for t in [0.2, 0.3, 0.4, 0.5]:
pred = (proba >= t).astype(int)
tn, fp, fn, tp = confusion_matrix(yte, pred).ravel()
print(t, "total cost:", fn * cost_missed + fp * cost_visit)
Typical total costs on the test set: about 5.96 million RWF at threshold 0.2, 8.04 million at 0.3, 11.14 million at 0.4 and 13.47 million at 0.5. With these costs, a low threshold is cheapest. If a follow-up visit were much more expensive, the best threshold would move up. Change the two costs and see how the answer changes.
Step 4: Cross-validation and feature importance
rf = models["Random forest"]
scores = cross_val_score(rf, Xtr, ytr, cv=5, scoring="roc_auc")
print("CV AUC: %.3f +/- %.3f" % (scores.mean(), scores.std()))
imp = pd.Series(rf.feature_importances_, index=X.columns).sort_values()
imp.plot.barh(title="Random forest feature importance"); plt.show()
Which feature matters most? Does that make sense to a loan officer?
Step 5: Fairness check
pred = models["Logistic regression"].predict(Xte)
audit = []
for g, label in [(0, "Rural"), (1, "Urban")]:
mask = (gte == g).values
audit.append({"group": label, "n": int(mask.sum()),
"flagged_rate": pred[mask].mean(),
"recall": recall_score(yte[mask], pred[mask])})
print(pd.DataFrame(audit).round(3))
In this simulated data the two groups have similar flagged rates (about 16%) and recall (about 0.36), because the groups were generated almost alike. A small gap here does not prove a model is fair in real life. Real groups differ in data quality and history. Write three questions you would ask before using this model on real borrowers.
Deliverables
- A notebook with all steps, outputs and short explanations.
- The completed model comparison table with your own numbers.
- A one-paragraph recommendation to the institution: chosen model, threshold, expected cost and limits.
- A model card using the template in Appendix F.
Marking guide
| Criterion | Points |
|---|---|
| Correct split, pipeline and no data leakage | 20 |
| Five models compared with suitable metrics | 20 |
| Threshold analysis and cost reasoning | 20 |
| Interpretation of overfitting and feature importance | 15 |
| Fairness check and honest limits | 15 |
| Clear recommendation | 10 |
| Total | 100 |
Extension tasks
- Add gradient boosting (
HistGradientBoostingClassifier) and compare. - Use
class_weight="balanced"in logistic regression and see how recall changes. - Train a small neural network (
MLPClassifier) and compare AUC with the forest. - Plot ROC curves for all models in one chart.
Week 4: Big Data, Applied AI and Capstone
Goal of the week: scale up your analysis, apply modern AI responsibly, and complete a capstone project. By Friday you will have processed data with Spark, used cloud and SQL tools, worked with large language models and presented a full project.
Session 1: Big Data Concepts, Hadoop and Apache Spark
Learning objectives
- Explain why big data needs distributed computing.
- Describe the Hadoop ecosystem and where Spark fits.
- Run basic PySpark operations on a dataset.
Theory: when data outgrows one computer
A single laptop has limited memory and processing power. When data no longer fits in memory, or processing takes too long, we distribute the work: split the data across many machines (a cluster), process the pieces in parallel, and combine the results. This is horizontal scaling, as opposed to vertical scaling (buying a bigger machine).
Before moving to big data tools, check whether you need them. Many
“big” problems fit comfortably on one computer with efficient code (use
usecols, correct data types, reading in chunks, or the
Parquet format). Distributed systems add complexity and cost, so use
them when the data or the speed requirement demands it.
The Hadoop ecosystem
Apache Hadoop was the first widely adopted open-source framework for distributed storage and processing.
| Component | Role |
|---|---|
| HDFS (Hadoop Distributed File System) | Splits files into blocks and stores copies on several machines for reliability |
| MapReduce | The original processing model: map (process pieces in parallel) then reduce (combine results) |
| YARN | Manages cluster resources and schedules jobs |
| Hive | Lets you query large datasets using SQL-like language |
| HBase | A database for fast reads and writes on huge tables |
Word count example in MapReduce thinking: many machines each count words in their part of the text (map), then the counts for the same word are added together (reduce).
Apache Spark
Apache Spark is a fast, general-purpose engine for large-scale data processing. It keeps data in memory between steps, which makes it much faster than classic MapReduce for many tasks, especially iterative ones such as machine learning.
Key ideas:
- DataFrame: a distributed table, very similar in feel to a pandas DataFrame.
- Lazy evaluation: Spark records your transformations (filter, select, group) and only runs them when an action (show, count, write) asks for a result. This lets it plan the most efficient route.
- Partitions: the pieces of data processed in parallel.
- Components: Spark SQL (queries), Spark MLlib (machine learning), Structured Streaming (live data).
| pandas | PySpark | |
|---|---|---|
| Runs on | One machine | A cluster (or one machine in local mode) |
| Best for | Up to a few gigabytes | Large data and distributed processing |
| Evaluation | Immediate | Lazy |
| Typical use | Analysis and prototyping | Production pipelines on big data |
Hands-on lab: PySpark in Colab
!pip install -q pyspark
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
spark = SparkSession.builder.master("local[*]").appName("week4").getOrCreate()
Create a sample of mobile money style transactions (simulated):
import numpy as np
import pandas as pd
rng = np.random.default_rng(5)
n = 500_000
pdf = pd.DataFrame({
"tx_id": np.arange(n),
"district": rng.choice(["Gasabo", "Huye", "Musanze", "Rubavu", "Nyagatare"], n),
"type": rng.choice(["send", "cashout", "airtime", "bill"], n, p=[.4, .3, .2, .1]),
"amount": rng.lognormal(8.5, 1.0, n).round(0),
"hour": rng.integers(0, 24, n),
})
pdf.to_parquet("tx.parquet")
Now work with it in Spark:
df = spark.read.parquet("tx.parquet")
df.printSchema()
print(df.count())
df.show(5)
# transformations (lazy) and an action (show)
summary = (df
.filter(F.col("amount") > 1000)
.groupBy("district", "type")
.agg(F.count("*").alias("n"),
F.round(F.avg("amount"), 0).alias("avg_amount"),
F.sum("amount").alias("total_amount"))
.orderBy(F.desc("total_amount")))
summary.show(10)
# add a column
df2 = df.withColumn("is_night", (F.col("hour") < 6) | (F.col("hour") >= 22))
df2.groupBy("is_night").count().show()
# convert a small result to pandas for plotting
result = summary.limit(20).toPandas()
Spark SQL lets you use SQL on the same data:
df.createOrReplaceTempView("transactions")
spark.sql("""
SELECT district, COUNT(*) AS n, ROUND(AVG(amount)) AS avg_amount
FROM transactions
WHERE type = 'cashout'
GROUP BY district
ORDER BY n DESC
""").show()
Machine learning at scale uses pyspark.ml:
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import LogisticRegression
data = df.withColumn("label", (F.col("amount") > 5000).cast("int"))
assembler = VectorAssembler(inputCols=["hour"], outputCol="features")
train = assembler.transform(data).select("features", "label")
model = LogisticRegression().fit(train)
print(model.coefficients)
Open the Spark UI (or call df.explain()) to see how
Spark plans the work. Local mode on Colab teaches the same code that
would run on a real cluster.
Spark compared with classic MapReduce
| Feature | Hadoop MapReduce | Apache Spark |
|---|---|---|
| Processing | Reads from and writes to disk between steps | Keeps data in memory between steps |
| Speed on iterative work | Slower | Often much faster |
| Programming | Lower-level, more code | DataFrame, SQL, Python, Scala, R |
| Machine learning | External tools | Built in (MLlib) |
| Streaming | Not designed for it | Structured Streaming |
| Typical use today | Legacy batch jobs | Analytics, pipelines and ML |
Data formats for big data
| Format | Type | Notes |
|---|---|---|
| CSV | Row-based text | Easy but large and slow; no types |
| JSON | Row-based text | Flexible, nested data |
| Parquet | Column-based binary | Compressed, fast, keeps types: the standard choice |
| ORC | Column-based binary | Common in the Hadoop world |
Column-based formats let you read only the columns you need, which saves time and money.
Key takeaways
- Distributed computing splits data and work across machines; Hadoop introduced it and Spark made it faster and easier.
- Spark DataFrames feel like pandas but are lazy and distributed.
- Use Parquet for large data, and do not use big data tools when a laptop is enough.
Practice exercises
- Compute the average transaction amount by hour of day in PySpark and plot it.
- Explain lazy evaluation to a classmate and give one benefit.
- Convert a CSV of at least 100,000 rows to Parquet and compare the file sizes.
Session 2: SQL at Scale, Data Warehouses, Data Lakes and Cloud Platforms
Learning objectives
- Write analytical SQL with joins, aggregations and window functions.
- Distinguish data warehouses, data lakes and lakehouses.
- Describe the main cloud services for data and AI.
Theory: SQL for analytics
SQL remains the most important language for working with data in
organizations. Beyond basic SELECT, analysts use
joins, aggregations,
subqueries and window functions.
Create sample tables to practice (SQLite in Python):
import sqlite3, pandas as pd, numpy as np
conn = sqlite3.connect(":memory:")
rng = np.random.default_rng(2)
customers = pd.DataFrame({
"customer_id": range(1, 201),
"district": rng.choice(["Gasabo", "Huye", "Musanze", "Rubavu"], 200),
"joined": pd.date_range("2025-01-01", periods=200, freq="D").astype(str),
})
tx = pd.DataFrame({
"tx_id": range(1, 3001),
"customer_id": rng.integers(1, 201, 3000),
"amount": rng.lognormal(8.5, 0.9, 3000).round(0),
"tx_date": pd.date_range("2026-01-01", periods=3000, freq="2h").astype(str),
})
customers.to_sql("customers", conn, index=False)
tx.to_sql("transactions", conn, index=False)
def q(sql): return pd.read_sql(sql, conn)
Join and aggregate:
q("""
SELECT c.district, COUNT(*) AS n_tx, ROUND(SUM(t.amount)) AS total
FROM transactions t
JOIN customers c ON c.customer_id = t.customer_id
GROUP BY c.district
HAVING COUNT(*) > 100
ORDER BY total DESC
""")
WHERE filters rows before grouping; HAVING
filters groups after aggregation.
Common table expressions (CTEs) make queries readable by naming steps:
q("""
WITH per_customer AS (
SELECT customer_id, COUNT(*) AS n, SUM(amount) AS total
FROM transactions
GROUP BY customer_id
)
SELECT * FROM per_customer
WHERE total > (SELECT AVG(total) FROM per_customer)
ORDER BY total DESC
LIMIT 10
""")
Window functions compute values across related rows without collapsing them:
q("""
SELECT customer_id, tx_date, amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY tx_date) AS running_total,
RANK() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS amount_rank
FROM transactions
WHERE customer_id <= 3
ORDER BY customer_id, tx_date
""")
SQL at scale: practical habits
- Select only the columns you need; avoid
SELECT *on big tables. - Filter early, especially on partition columns such as date, so the engine reads less data.
- Use indexes (in traditional databases) or partitioning and clustering (in warehouses).
- Check the query plan with
EXPLAIN. - Be careful with joins that multiply rows; check counts before and after.
Databases, warehouses, lakes and lakehouses
| Operational database (OLTP) | Data warehouse (OLAP) | Data lake | Lakehouse | |
|---|---|---|---|---|
| Purpose | Run the business: record each transaction | Analyze: reports and dashboards | Store everything cheaply in raw form | Combine lake storage with warehouse features |
| Data | Current, detailed | Cleaned, structured, historical | Structured, semi-structured and unstructured | All types with table management |
| Schema | Fixed before writing | Fixed before writing | Applied when reading | Flexible with governance |
| Example technology | PostgreSQL, MySQL | BigQuery, Redshift, Snowflake, Synapse | Cloud object storage with files | Delta Lake, Apache Iceberg |
ETL (extract, transform, load) moves data from sources into a warehouse after cleaning it. ELT loads raw data first and transforms it inside the warehouse. Tools like Apache Airflow schedule and monitor such data pipelines.
Cloud platforms
Cloud providers rent computing and storage on demand, so organizations pay for what they use instead of buying servers.
| Need | AWS | Microsoft Azure | Google Cloud |
|---|---|---|---|
| Object storage | S3 | Blob Storage | Cloud Storage |
| Data warehouse | Redshift | Synapse | BigQuery |
| Managed Spark | EMR, Glue | Databricks, Synapse | Dataproc |
| ML platform | SageMaker | Azure Machine Learning | Vertex AI |
Service names change over time, so check each provider’s documentation for the current list.
Cloud considerations:
- Cost: watch usage, delete unused resources and set budget alerts. A forgotten cluster can be expensive.
- Security: control who can access what (least privilege), encrypt data, and never put secret keys in code.
- Data location and law: personal data may be subject to rules about where it can be stored and processed.
- Free tiers and student credits exist for learning; read the terms carefully.
Hands-on lab
- Run the join, CTE and window function queries above and explain each result in one sentence.
- Write a query that finds the top customer in each district (hint:
window function with
ROW_NUMBERorRANK). - Sign up for a free-tier account on one cloud platform (or use the sandbox your instructor provides) and upload your Parquet file to object storage. Do not upload personal data.
Key takeaways
- Master joins,
GROUP BY, CTEs and window functions; they cover most analytics needs. - Warehouses serve analysis; lakes store raw data; lakehouses combine both.
- Cloud brings flexibility but requires attention to cost, security and legal rules.
Practice exercises
- Explain the difference between
WHEREandHAVINGwith an example. - Draw a simple pipeline diagram for a mobile money provider that moves daily transactions into a warehouse for reporting.
- List three controls that protect a cloud storage bucket holding sensitive data.
Session 3: Generative AI, Large Language Models and Prompt Engineering
Learning objectives
- Explain how large language models (LLMs) work at a high level.
- Describe their strengths and limits, including hallucination.
- Write effective prompts and use AI assistants safely for data work.
Theory: what is generative AI?
Generative AI creates new content such as text, images, code, audio or video. Large language models are generative models trained on very large collections of text to predict the next piece of text (a token). By learning this simple task at huge scale, they pick up grammar, facts, reasoning patterns and writing styles.
How LLMs work (simplified)
- Tokenization: text is split into tokens (words or word pieces) and converted into numbers.
- Embeddings: each token becomes a vector of numbers that captures meaning, so related words end up close together.
- Transformer network: layers of attention let the model weigh which earlier tokens matter most for the next one.
- Pre-training: the model learns to predict the next token over huge amounts of text.
- Fine-tuning and alignment: further training on examples of good answers and human feedback makes the model follow instructions and be more helpful and safer.
- Generation: the model produces one token at a time, sampling from its predicted probabilities. A temperature setting controls randomness: low for consistent answers, higher for more varied ones.
The context window is the amount of text the model can consider at once. It does not remember earlier conversations unless they are included.
Strengths and limits
| Strengths | Limits |
|---|---|
| Drafting, summarizing, rewriting, translating | Hallucination: can state false things confidently |
| Explaining concepts and code | Knowledge has a cutoff date unless connected to search |
| Generating and debugging code | May reflect biases found in training data |
| Brainstorming and structuring ideas | Weaker with rare languages and local context, including Kinyarwanda |
| Extracting information from text | Can be inconsistent; not a calculator or a guaranteed source of truth |
Never trust AI output blindly. Verify facts, run and test code, check calculations, and cite original sources, not the AI.
Prompt engineering
A prompt is the instruction you give the model. Better prompts give better answers. A strong prompt contains:
- Role or context: who the model should act as and what situation it is in.
- Task: exactly what you want done.
- Input data: the material to work on.
- Constraints: length, tone, audience, things to avoid.
- Output format: a table, a list, JSON, code.
- Examples: one or two samples of the desired result (called few-shot prompting).
Weak prompt: “Analyze my data.”
Better prompt:
You are a data analyst helping a district health office. Below is a summary table of monthly clinic visits (columns: month, facility, visits, stock_outs). Identify the three most important trends, explain each in one sentence for a non-technical manager, and suggest one question to investigate next. Return the answer as a numbered list. Do not invent numbers that are not in the table.
Useful techniques
- Step-by-step reasoning: ask the model to work through a problem in stages and show its reasoning for checking.
- Few-shot examples: show two or three input and output pairs.
- Structured output: request JSON so a program can read the result.
- Iterate: treat the first answer as a draft. Ask for changes: “shorter”, “for a farmer audience”, “add a risk section”.
- Ask for uncertainty: “If you are not sure, say so.”
- Ground the model in sources: paste the relevant text and say “answer only from the text below”. This is the idea behind retrieval-augmented generation (RAG), where a system first retrieves relevant documents and gives them to the model.
Prompt patterns you can reuse
| Pattern | Template | Example use |
|---|---|---|
| Role and task | “You are a [role]. Do [task] for [audience].” | Explain a chart to a district manager |
| Step by step | “Work through this in numbered steps and show your reasoning.” | Checking a statistics calculation |
| Few-shot | “Here are two examples of input and output. Now do the same for…” | Extracting dates and districts from reports |
| Grounded answer | “Answer only from the text below. If it is not there, say so.” | Questions on a policy document |
| Structured output | “Return valid JSON with keys district, date, cases.” | Turning text into a table |
| Critique | “Review the answer above and list three possible errors.” | Catching hallucinations |
| Rewrite | “Rewrite for a secondary-school student in under 100 words.” | Simplifying explanations |
Using AI assistants for data work
Good uses: explaining an error message, suggesting a pandas approach, writing a first draft of a chart, generating test data, writing documentation, summarizing a report.
Risks and good habits:
- Do not paste personal, confidential or sensitive data into public AI tools. Anonymize or use fake data.
- Test generated code on small examples and compare with a manual calculation.
- Understand before you use. If you cannot explain a line of code, you cannot defend the analysis.
- Keep records: note which parts were AI-assisted, following your institution’s rules on academic honesty and disclosure.
Hands-on lab: prompt workshop
Work in pairs and use the AI assistant approved by your instructor. Do not enter personal data.
- Improve a prompt. Start with the weak prompt “Explain machine learning” and improve it in three steps. Compare the results.
- Data task. Paste a small, anonymous table (10 rows) and ask the assistant to summarize it. Then check every number it states.
- Code task. Ask for pandas code that computes the average yield per district. Run it and fix any errors.
- Structured output. Ask the assistant to extract the district, date and number of cases from three short report sentences and return JSON.
- Catch a hallucination. Ask a question about a very specific local fact and check the answer against an official source. Report what you found.
Optional: call an LLM from Python, using the provider’s documentation and your own API key stored in an environment variable, never in code you share:
import os
# Example structure only: follow your provider's current documentation.
api_key = os.environ.get("LLM_API_KEY") # keep secrets out of your code
prompt = "Summarize this table for a district manager in three bullet points:\n..."
# response = client.generate(prompt=prompt) # method names differ by provider
Key takeaways
- LLMs predict the next token using transformer networks trained at huge scale.
- They are powerful drafting and coding helpers but can hallucinate, so always verify.
- Good prompts state role, task, data, constraints, format and examples.
- Protect sensitive data and be transparent about AI use.
Practice exercises
- Write a prompt that makes an assistant explain “overfitting” to a secondary school student, in under 100 words, using a local example.
- Find one factual error in an AI answer and describe how you detected it.
- Design a RAG workflow on paper for a help desk that answers questions from a set of policy documents.
Session 4: Responsible AI: Ethics, Bias, Privacy and Data Protection
Learning objectives
- Identify sources of bias in data and models.
- Apply principles of fairness, transparency, accountability and privacy.
- Describe the main ideas of data protection law and apply them to a project.
Theory: why responsible AI?
AI systems are used to make decisions about loans, jobs, health care, education and public services. When they fail, real people are harmed, and the harm often falls on groups who are already disadvantaged. Responsible AI means building and using AI so that it is fair, transparent, accountable, private, safe and beneficial.
Where bias comes from
| Source | Example |
|---|---|
| Historical bias | Past lending records reflect past discrimination, and the model learns to repeat it |
| Sampling bias | A health model trained mostly on urban hospital data performs poorly for rural patients |
| Measurement bias | Using “number of hospital visits” as a proxy for “health need” misses people who cannot reach hospitals |
| Label bias | Human annotators bring their own prejudices to labels |
| Representation bias | Language models trained mostly on English perform worse on Kinyarwanda |
| Deployment bias | A tool built for one purpose is used in a different setting |
| Proxy variables | Removing “gender” does not help if postal code or occupation acts as a stand-in |
Fairness: it is not a single number
Different definitions of fairness exist, and they can conflict:
- Demographic parity: each group receives positive decisions at the same rate.
- Equal opportunity: among people who truly qualify, each group has the same chance of being approved (equal recall).
- Calibration: a risk score of 70% should mean about 70% for every group.
Choosing a definition is an ethical and legal decision that involves the people affected, not only a technical one.
A simple bias audit
import pandas as pd
from sklearn.metrics import recall_score, precision_score
# test_df has: y_true, y_pred, and a group column (for example "urban"/"rural")
def audit(test_df, group_col):
rows = []
for g, part in test_df.groupby(group_col):
rows.append({
group_col: g,
"n": len(part),
"approval_rate": part["y_pred"].mean(),
"recall": recall_score(part["y_true"], part["y_pred"]),
"precision": precision_score(part["y_true"], part["y_pred"]),
})
return pd.DataFrame(rows)
# print(audit(test_df, "urban"))
Large differences in approval rate or recall between groups call for investigation: better data, different features, adjusted thresholds, or a decision not to automate that task.
Transparency and accountability
- Explainability: people affected by a decision should receive a meaningful explanation. Use interpretable models where stakes are high.
- Documentation: record the data sources, intended use, limits and test results (for example in a model card and a datasheet for datasets).
- Human oversight: a person must be able to review, challenge and override important automated decisions.
- Accountability: someone must be responsible when a system causes harm, and there must be a way to appeal.
- Monitoring: check performance and fairness after deployment, as data and behavior drift over time.
Privacy and data protection
Personal data is information that identifies a person or can be linked to one: names, phone numbers, national ID numbers, location traces, health records, and combinations that single someone out. Removing the name is often not enough, because other columns can re-identify a person.
Most data protection laws, including Rwanda’s law on the protection of personal data and privacy (enacted in 2021), build on similar principles. The summary below is for learning and is not legal advice; check the current text of the law and your organization’s policies.
| Principle | What it means in practice |
|---|---|
| Lawfulness and consent | Have a legal basis, often clear consent, to collect and use data |
| Purpose limitation | Use data only for the purpose it was collected for |
| Data minimization | Collect and keep only what you need |
| Accuracy | Keep data correct and up to date |
| Storage limitation | Delete data when it is no longer needed |
| Security | Protect data with access control and encryption |
| Individual rights | People can ask to access, correct or delete their data, subject to the law |
| Accountability | Be able to show that you comply; report breaches as required |
Technical protections: anonymization and pseudonymization, aggregation, access control, encryption in storage and transfer, audit logs, and privacy techniques such as differential privacy and federated learning, which train models without collecting raw data in one place.
Other responsible AI concerns
- Safety and misuse: consider how a system could be abused (for example deepfakes or scams) and add safeguards.
- Environmental cost: training large models uses substantial energy; choose appropriately sized models.
- Labor and inclusion: involve local communities, build local skills and data, and avoid extractive data collection.
- Intellectual property and honesty: respect licenses and copyright, and disclose AI-generated content where required.
- Local and national policy: governments and institutions publish AI strategies and guidance. Follow those that apply to your sector.
A simple ethics checklist for any AI project
- What problem are we solving, and for whom? Is AI the right tool?
- Who could be harmed, and how? Have we asked them?
- Is the data lawful, representative and minimal?
- Have we tested performance across different groups?
- Can decisions be explained and appealed?
- How is data secured, and when is it deleted?
- Who is accountable, and how will we monitor after launch?
Hands-on lab: bias audit exercise
- Take the loan model from Week 3 and add a simulated column
urban(random 0 or 1, with rural applicants having slightly lower recorded incomes). - Run the audit function on the test predictions.
- Report approval rates and recall by group. Is there a gap?
- Propose two actions (for example collect better data or review thresholds) and one reason not to deploy the system without further checks.
- Write a short “model card”: purpose, data, metrics, limits and intended users.
Key takeaways
- Bias can enter at every stage: data, labels, features, deployment.
- Fairness has several definitions that can conflict; choose with those affected.
- Respect privacy by minimizing data, protecting it and following the law.
- Transparency, human oversight and monitoring keep AI accountable.
Practice exercises
- Give an example of a proxy variable that could cause unfair results in a hiring model.
- List the personal data in a typical health clinic record and decide which fields a research analyst really needs.
- Write three questions you would ask a vendor who offers an AI tool to your institution.
Session 5: Capstone Presentations and Course Closure
Learning objectives
- Plan, document and present a complete data science project.
- Give and receive constructive feedback.
- Plan the next steps for your learning and career.
The capstone project
Work in groups of three or four on a real problem. You will use the full lifecycle: question, data, cleaning, EDA, modeling, evaluation, communication and responsible AI.
Possible themes
- Health: forecast clinic visits or stock needs from monthly facility data.
- Agriculture: predict yield or classify risk using rainfall, fertilizer and district data.
- Finance and mobile money: build a fraud or default risk model with open or simulated data.
- Education: analyze exam results and factors linked to performance.
- Public services and cities: analyze transport, energy or waste data.
- Language and text: classify or summarize short texts, including Kinyarwanda where data exists.
Deliverables
- A documented notebook that runs from start to finish.
- A short report or dashboard (two to four pages or screens) for a non-technical audience.
- A 10-minute presentation followed by questions.
- A responsible AI note: data source and permission, possible bias, privacy protections and limits.
Capstone timeline across the week
| Day | Milestone |
|---|---|
| Monday to Tuesday | Choose the topic and question; find and check data; write a one-paragraph plan |
| Wednesday | Data cleaning and EDA complete |
| Thursday | Models and evaluation complete; responsible AI note drafted; rehearse |
| Friday | Presentations, feedback, closing |
Project structure for the notebook
- Title, team and question
- Data sources and permissions
- Cleaning steps and a data quality summary
- Exploratory analysis with key charts
- Modeling: baseline first, then improved models
- Evaluation on a test set with suitable metrics
- Interpretation: what the model tells us and what it does not
- Responsible AI note and limits
- Recommendations and next steps
Evaluation rubric (suggested)
| Criterion | Weight | What strong work shows |
|---|---|---|
| Problem framing | 15% | A clear question and a real user or decision |
| Data work | 20% | Documented cleaning, quality checks, lawful and ethical data use |
| Analysis and modeling | 25% | Appropriate methods, a baseline, honest evaluation on unseen data |
| Communication | 20% | Clear visuals and plain-language storytelling |
| Responsible AI | 10% | Bias, privacy and limits considered seriously |
| Teamwork and reproducibility | 10% | Code runs, work is shared fairly |
Presentation guide: 10 minutes
- The problem (1 minute): who cares and why?
- The data (1 minute): source, size, quality.
- The method (2 minutes): what you did and why.
- The findings (3 minutes): the three most important results, with charts.
- Limits and responsible AI (1 minute): what could go wrong.
- Recommendations (1 minute): what should happen next.
- Questions (1 minute).
Tips: one message per slide, large readable charts, no walls of text, practice with a timer, and let every team member speak.
Giving feedback
Use the format “One thing I liked, one question, one suggestion.” Be specific and kind. Feedback improves everyone’s work.
Course closure: what next?
Keep practicing
- Build a small project every month and publish it (for example on GitHub) without personal data.
- Join data communities and local meetups; take part in open data and hackathon events.
- Compete in learning platforms such as Kaggle to practise on varied problems.
Learning paths
| Goal | Next steps |
|---|---|
| Data analyst | Deepen SQL, Power BI or Tableau, statistics, communication |
| Data scientist | More statistics, feature engineering, model deployment, experiment design |
| Data engineer | Python and SQL at scale, Spark, Airflow, cloud data services |
| ML engineer | Software engineering, MLOps, deep learning frameworks, monitoring |
| Researcher or lecturer | Advanced statistics and ML theory, reproducible research, publishing |
Career habits: keep a portfolio, document your work, learn to explain results simply, and stay curious about the ethics of the tools you build.
Certificate and wrap-up
Participants who complete the course requirements receive a certificate of completion. Complete the course feedback form so future cohorts benefit from your experience.
Key takeaways
- A complete project joins problem, data, analysis, communication and ethics.
- Clear communication turns analysis into action.
- Learning continues after the course through projects, community and practice.
Practice exercises
- Write a one-page plan for your next personal data project.
- Present your capstone in three minutes to someone outside your field and note which parts confused them.
- List the five skills from this course you will practise first, with a date for each.
Practical Workshop 4: Pipeline, Prompts and Responsible AI
Time: 3 hours. Work: teams of three or four. Tools: Google Colab (pandas, SQLite, PySpark), an approved AI assistant.
This workshop has four short labs that mirror a real project: build a data pipeline, query it with SQL, use AI assistance carefully, and audit the result for fairness and privacy. All data is simulated.
Lab A: Build a small data pipeline (50 minutes)
Goal: create a repeatable pipeline that turns raw transactions into a clean table and a monthly report.
import numpy as np
import pandas as pd
import sqlite3
rng = np.random.default_rng(4)
n = 20000
raw = pd.DataFrame({
"tx_id": np.arange(n),
"customer_id": rng.integers(1, 1501, n),
"district": rng.choice(["Gasabo", "Huye", "Musanze", "Rubavu", "gasabo", None], n,
p=[.28, .2, .2, .2, .07, .05]),
"type": rng.choice(["send", "cashout", "airtime", "bill"], n, p=[.4, .3, .2, .1]),
"amount": rng.lognormal(8.5, 1.0, n).round(0),
"tx_time": pd.Timestamp("2026-01-01") + pd.to_timedelta(rng.integers(0, 120 * 24 * 60, n), unit="m"),
})
raw.loc[rng.choice(n, 40, replace=False), "amount"] = -1 # invalid
raw = pd.concat([raw, raw.sample(100, random_state=0)], ignore_index=True) # duplicates
def extract(): return raw.copy()
def transform(df):
df = df.drop_duplicates(subset="tx_id")
df = df[df["amount"] > 0].copy()
df["district"] = df["district"].fillna("Unknown").str.title()
df["month"] = df["tx_time"].dt.to_period("M").astype(str)
df["is_night"] = (df["tx_time"].dt.hour < 6) | (df["tx_time"].dt.hour >= 22)
return df
def load(df, path="warehouse.db"):
conn = sqlite3.connect(path)
df.assign(tx_time=df["tx_time"].astype(str)).to_sql("transactions", conn,
if_exists="replace", index=False)
conn.close()
clean = transform(extract())
load(clean)
print(len(raw), "raw rows ->", len(clean), "clean rows")
Tasks
- Run the pipeline and record how many rows were removed and why (duplicates and invalid amounts).
- Add a data quality check that stops the pipeline if any amount is
not positive (use
assert). - Draw your pipeline on paper in the style of Figure 19 (extract, transform, load, report).
Expected: 20,100 raw rows become 19,960 clean rows (100 duplicate rows and 40 invalid amounts removed). Check that your own numbers match.
Lab B: Analytical SQL (40 minutes)
conn = sqlite3.connect("warehouse.db")
def q(sql): return pd.read_sql(sql, conn)
q("""
SELECT month, district, COUNT(*) AS n_tx, ROUND(SUM(amount)) AS total_rwf
FROM transactions
GROUP BY month, district
ORDER BY month, total_rwf DESC
""").head(10)
Complete the table by writing the SQL for each question.
| Question | SQL ideas |
|---|---|
| What is the total value by transaction type? | GROUP BY type with SUM(amount) |
| Which five customers have the highest total value? | GROUP BY customer_id, ORDER BY,
LIMIT 5 |
| What share of transactions happen at night? | AVG(is_night) |
| What is each district’s value as a share of the total? | SUM(amount) * 1.0 / (SELECT SUM(amount) FROM transactions) |
| What is the running monthly total per district? | Window function
SUM(...) OVER (PARTITION BY district ORDER BY month) |
| Which customers are in the top 1% by value? | CTE plus NTILE(100) or a subquery |
q("""
WITH monthly AS (
SELECT district, month, SUM(amount) AS total
FROM transactions GROUP BY district, month
)
SELECT district, month, total,
SUM(total) OVER (PARTITION BY district ORDER BY month) AS running_total
FROM monthly
ORDER BY district, month
""")
Lab C: The same analysis in PySpark (40 minutes)
Run in Colab. Save the cleaned data as Parquet, then reproduce one SQL result with Spark.
clean.to_parquet("clean_tx.parquet")
!pip install -q pyspark
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[*]").getOrCreate()
sdf = spark.read.parquet("clean_tx.parquet")
(sdf.groupBy("district", "type")
.agg(F.count("*").alias("n"), F.round(F.sum("amount")).alias("total"))
.orderBy(F.desc("total"))
.show(10))
Tasks
- Check that the Spark totals equal your SQL totals (they must match).
- Run
sdf.explain()and identify the scan and the aggregation steps. - Write one sentence: for this dataset, did you really need Spark? Why or why not?
Lab D: AI assistant and responsible AI audit (50 minutes)
D1. Prompt lab. Use an approved AI assistant with no real personal data. Improve each prompt in the table, then verify the output against your own results from Lab B.
| Task | Weak prompt | Your improved prompt | Did you verify the answer? |
|---|---|---|---|
| Explain a result | “Explain this data” | ||
| Write SQL | “Write SQL for sales” | ||
| Summarize for a manager | “Summarize” | ||
| Find errors | “Is this code okay?” |
D2. Bias audit. Imagine the provider uses this data to decide which customers get an offer for a larger mobile loan. Answer in the table.
| Question | Your answer |
|---|---|
| Which columns could be proxies for sensitive characteristics? | |
| Which groups could be missing or under-represented in this data? | |
| Which personal data should be removed or pseudonymized before analysis? | |
| What would you measure to check fairness between districts? | |
| What human review and appeal process is needed? |
D3. Short model card and risk note. Using the templates in Appendix F, write a half-page note covering purpose, data, limits and risks.
Deliverables
- The pipeline notebook (Lab A) with a data quality check.
- SQL answers for the questions in Lab B.
- The Spark notebook (Lab C) with the verification.
- The completed prompt table and the bias audit table (Lab D).
Marking guide
| Criterion | Points |
|---|---|
| Working, documented pipeline with a quality check | 25 |
| Correct SQL answers | 25 |
| Spark results that match SQL | 15 |
| Prompts improved and outputs verified | 15 |
| Thoughtful bias, privacy and risk analysis | 20 |
| Total | 100 |
Extension tasks
- Schedule the pipeline with a simple function that runs it for each day of the data.
- Add a fraud rule (for example a transaction more than five times the customer’s average) and list flagged cases for human review.
- Compare file sizes of the CSV and Parquet versions and report the saving.
Supplementary Modules for the AI for Africa Certificate
These five modules add topics from the certificate that the weekly sessions only touch. Each module can be read in about one to two hours.
Module S1: Artificial Intelligence: Past, Present and Future
Learning objectives
- Place today’s AI in historical context.
- State what current AI does well and where it fails.
- Discuss likely directions for the future.
A short timeline
| Period | Milestone | Lesson |
|---|---|---|
| 1950s | Alan Turing asks whether machines can think; the 1956 Dartmouth workshop names the field “artificial intelligence” | AI began as a research question |
| 1960s to 1980s | Rule-based expert systems; early optimism, then “AI winters” when results fell short of promises | Hype cycles are normal |
| 1990s | Statistical machine learning; IBM’s Deep Blue beats the chess champion in 1997 | Data and computing power matter |
| 2012 | A deep neural network wins a major image recognition contest | Deep learning takes off with GPUs and big data |
| 2017 | The transformer architecture is introduced | The basis of modern language models |
| 2022 onward | Chat-based generative AI reaches the public | AI becomes a general-purpose tool |
Capabilities and limitations
| AI tools do well | AI tools do poorly |
|---|---|
| Finding patterns in large data | Understanding context and common sense reliably |
| Classifying images, speech and text | Explaining their own reasoning faithfully |
| Drafting, summarizing and translating | Staying factual (they can hallucinate) |
| Automating repetitive tasks | Handling situations unlike their training data |
| Predicting from past data | Fair decisions when data is biased |
Purpose test: before using AI, ask what decision it supports, what happens when it is wrong, and whether a simpler method would work.
The future: questions to discuss
- Which jobs will change, and what skills stay valuable?
- How will smaller, cheaper models and on-device AI affect places with limited connectivity?
- Who sets the rules: governments, companies or communities?
- How do we keep humans responsible for important decisions?
Practice exercises
- Choose one milestone in the timeline and explain in 100 words why it mattered.
- List three tasks in your work that AI could help with and three that it should not do alone.
Module S2: AI and Machine Learning in Africa
Learning objectives
- Describe how AI is being applied to African problems.
- Identify the specific data, infrastructure and language challenges.
- Frame a locally relevant problem.
Opportunities by sector
| Sector | Example problem | Typical data | Special challenge |
|---|---|---|---|
| Health | Predict clinic demand; support screening from images | Facility reports, images, supply records | Patient privacy; uneven record quality |
| Agriculture | Estimate yield; detect crop disease from phone photos | Satellite images, weather, field photos | Few labeled local images; seasonal change |
| Finance | Credit scoring for people without bank history; fraud detection | Mobile money transactions | Fairness; consent; imbalanced classes |
| Education | Identify learners needing support | Exam and attendance records | Small data; ethical use of student data |
| Language | Speech and text tools for African languages | Recorded speech, written text | Low-resource languages with little data |
| Climate and cities | Flood and drought warning; traffic and waste planning | Sensors, satellite, mobile data | Sparse sensors; need for open data |
Challenges that shape solutions
- Data availability and quality: many datasets are small, scattered or on paper. Plan for data collection and cleaning first.
- Connectivity and devices: a solution that needs fast internet may fail in rural areas. Consider offline-capable apps, light models and SMS or USSD access.
- Language and culture: models trained mostly on English or Western data can perform poorly for Kinyarwanda, Swahili and other languages. Community efforts such as Masakhane (African language NLP) and open speech datasets for Kinyarwanda address this.
- Compute and cost: use small models, free tiers and efficient methods.
- Skills and community: meetups, the Deep Learning Indaba and data science competitions such as those on Zindi build local capacity.
- Policy and trust: national AI policies (Rwanda has a national AI policy) and the African Union’s continental AI strategy guide responsible adoption. Communities must benefit, and data should be used with consent.
Designing for context: a short checklist
- Who exactly are the users, and what do they have (phone type, connectivity, language)?
- Is the data representative of those users?
- Can the solution run where the users are?
- Who owns the data and benefits from the result?
- What local partner or expert can check the results?
Practice exercises
- Pick one sector in the table and write a one-page problem statement for your district.
- Redesign a cloud-only solution so it works with weak connectivity.
Module S3: Mathematical Foundations of Machine Learning
Learning objectives
- Use vectors and matrices to represent data and models.
- Explain derivatives and gradient descent.
- Apply probability rules and Bayes’ theorem to model uncertainty.
Linear algebra
A vector is a list of numbers, such as the features of one customer. A matrix is a table of numbers, such as a whole dataset (rows are records, columns are features).
| Idea | Meaning in machine learning |
|---|---|
| Dot product | A weighted sum: the core of linear models and neurons |
| Matrix multiplication | Predictions for all records at once |
| Transpose | Swaps rows and columns; used in the normal equation |
| Norm | The size of a vector; used in regularization |
| Eigenvectors | Directions of greatest variation; the basis of PCA |
import numpy as np
X = np.array([[1, 2], [3, 4], [5, 6]]) # 3 records, 2 features
w = np.array([0.5, -1.0]) # weights
print(X @ w) # predictions for all rows
print(X.T @ X) # a 2x2 matrix used in regression
C = np.cov(X.T) # covariance matrix of the features
vals, vecs = np.linalg.eigh(C)
print("variance along principal directions:", vals)
Calculus and optimization
The derivative tells how fast a function changes. For a model with loss , the gradient points uphill, so we step downhill: , where is the learning rate.
import numpy as np
rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 100)
y = 3.0 * x + 5 + rng.normal(0, 1, 100) # true slope 3, intercept 5
w, b, lr = 0.0, 0.0, 0.01
for step in range(2000):
pred = w * x + b
err = pred - y
w -= lr * (2 * (err * x).mean()) # d(MSE)/dw
b -= lr * (2 * err.mean()) # d(MSE)/db
print(round(w, 2), round(b, 2)) # close to 3 and 5
Try a very large lr (such as 0.1) and watch the training
fail to settle: that is an unstable learning rate.
Probability and uncertainty
- Expectation: the average outcome, . Variance: .
- Bayes’ theorem: . It tells us how to update beliefs after seeing evidence.
- Maximum likelihood: choose the parameters that make the observed data most probable. Least-squares regression is maximum likelihood when errors are normal.
| Concept | Where it appears |
|---|---|
| Distributions | Modeling noise, generating data |
| Conditional probability | Classifiers, false-alarm rates |
| Expectation and variance | Bias and variance of models |
| Bayes’ theorem | Naive Bayes, diagnostic tests |
Practice exercises
- Compute by hand for a 3×2 matrix and check with NumPy.
- Change the learning rate in the gradient descent code to 0.001, 0.01
and 0.05 and compare the final
w. - A disease affects 2% of people; a test finds 95% of cases and wrongly flags 4% of healthy people. Use Bayes’ theorem to find the chance that a positive result is correct.
Module S4: From Problem to Deployable Solution, and Measuring Impact
Learning objectives
- Turn a real-world challenge into a well-defined data and machine learning problem.
- Choose a deployment approach that fits the context.
- Validate a solution and judge its real impact, with critical thinking.
Step 1: Frame the problem
| Question | Example answer |
|---|---|
| Who has the problem? | Smallholder maize farmers in one district |
| What decision will the model support? | When to plant and how much fertilizer to buy |
| What is predicted? | Expected yield (a number) |
| What data exists, and is it enough? | Three seasons of yield and rain records |
| What is the simplest baseline? | The district average from last year |
| How will success be measured? | Prediction error, and farmers’ actual income or input savings |
Step 2: Choose a deployment approach
| Option | Good when | Trade-off |
|---|---|---|
| Batch reports (weekly file or dashboard) | Decisions are periodic | Not real time |
| Web or mobile app with an API | Users have connectivity | Needs a server and maintenance |
| Offline or on-device model | Weak connectivity | Smaller models; harder updates |
| SMS or USSD access | Feature phones | Limited interface |
| Human-in-the-loop tool | High-stakes decisions | Needs trained staff |
A trained scikit-learn model can be saved and served in a few lines:
import joblib
from sklearn.ensemble import RandomForestRegressor
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(200, 3)); y = X @ [1.0, 2.0, 0.5] + rng.normal(0, 0.1, 200)
model = RandomForestRegressor(n_estimators=100, random_state=0).fit(X, y)
joblib.dump(model, "yield_model.joblib") # save
model = joblib.load("yield_model.joblib") # load in the application
print(model.predict([[0.2, -0.1, 0.5]]))
A web service would load this file and expose a predict
endpoint (for example with FastAPI or Flask). Add input checks, logging
and a version number.
Step 3: Validate properly
| Technique | Purpose |
|---|---|
| Hold-out test set | Honest estimate on unseen data |
| Cross-validation | More stable estimate and tuning |
| Time-based split | Test on the future when predicting over time |
| Group split | Test on new districts or people, not only new rows |
| Baseline comparison | Check the model beats a simple rule |
| Error analysis | Find where and for whom the model fails |
| Pilot or A/B test | Measure effects in real use |
Step 4: Measure impact with a metric ladder
| Level | Question | Example metric |
|---|---|---|
| Model | Is it accurate? | MAE, recall, AUC |
| Product | Do people use it? | Weekly active users, completion rate |
| Outcome | Does it change decisions? | Share of farmers who changed fertilizer use |
| Impact | Is life better? | Yield or income change versus a comparison group |
| Risk | Who might be harmed? | Error rates by group; complaints |
Critical thinking checklist
- Does the evidence support the claim, or only a correlation?
- Compared with what? Is there a baseline or control group?
- Would the result hold in another district or season?
- What did we not measure? What are the costs and side effects?
- Who benefits and who may be left out?
Practical Workshop 5: Design a deployable solution
Work in a small group and complete the canvas for a problem in your community.
| Section | Your answer |
|---|---|
| Problem and users | |
| Decision supported | |
| Data needed and sources | |
| Baseline and model idea | |
| Metrics at the model, outcome and risk levels | |
| Deployment approach and why | |
| Validation plan | |
| Risks, privacy and fairness | |
| Pilot plan and success criteria |
Present the canvas in five minutes and answer two questions from another group.
Module S5: Applied Generative AI: Retrieval and Evaluation
Learning objectives
- Build a simple retrieval-augmented generation (RAG) workflow.
- Evaluate generative AI outputs systematically.
- Choose between prompting, RAG and fine-tuning.
Prompting, RAG or fine-tuning?
| Approach | Best for | Notes |
|---|---|---|
| Prompt engineering | Quick tasks, formats, style | Cheapest; try first |
| RAG | Answers grounded in your own documents | Reduces hallucination; easy to update |
| Fine-tuning | Consistent style or a specialized task | Needs data and expertise |
| Agents and tools | Multi-step tasks using search or code | Needs careful safety limits |
A minimal RAG pipeline
The steps are: split documents into chunks, find the chunks most relevant to the question, and place them in the prompt. This example uses simple keyword similarity (TF-IDF) so it runs with no extra service.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"Clinics report stock-outs on the first working day of each month.",
"Farmers should apply fertilizer after the first rains of the season.",
"Mobile money agents must verify the customer ID for transfers above the limit.",
"Cleaning data means fixing duplicates, types, missing values and outliers.",
]
vec = TfidfVectorizer().fit(docs)
D = vec.transform(docs)
def retrieve(question, k=2):
sims = cosine_similarity(vec.transform([question]), D)[0]
return [docs[i] for i in sims.argsort()[::-1][:k]]
question = "When should farmers apply fertilizer?"
context = "\n".join(retrieve(question))
prompt = (f"Answer only from the context. If the answer is not there, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}")
print(prompt) # send this prompt to your approved language model
Production systems replace TF-IDF with embeddings and a vector database, and cite the source passages in the answer.
Evaluating generative AI
| Dimension | Check |
|---|---|
| Accuracy and faithfulness | Does the answer match the sources? Any invented facts? |
| Relevance and completeness | Does it answer the question fully? |
| Safety and bias | Any harmful, unfair or private content? |
| Consistency | Same question, similar answer? |
| Cost and speed | Tokens used, response time |
Build a small test set of 20 to 50 real questions with reference answers, run the system on them after every change, and review failures manually.
Practice exercises
- Add three new documents to the RAG example and test five questions, including one that is not covered.
- Write five test questions for a help desk assistant and a checklist for scoring answers.
- Explain when you would choose RAG instead of fine-tuning.
Practice Guide and Tool Kit
This chapter turns the notes into a practice program for the six courses of the Certificate in AI for Africa. It gives a weekly plan, recommended tools, graded practice tasks with guidance, and advice for building a portfolio.
Part P1: How to practice
The practice cycle for every topic: (1) read or watch for 30 minutes, (2) type and run the examples, (3) change them and break them on purpose, (4) solve a task without looking, (5) write three lines on what you learned and what confused you.
Rules of thumb
- Practice little and often: five to six hours per week matches the certificate’s expected pace.
- Aim for working code first, then clean it, then explain it.
- Always compare with a baseline, and always keep a test set.
- Write down every assumption and every data source.
- Ask for help early, and share what you learn with a study partner.
Six-week practice plan (about 6 hours per week)
| Week | Focus (certificate course) | Practice tasks | Deliverable |
|---|---|---|---|
| 1 | Artificial Intelligence: Past, Present and Future | Tasks C1.1 to C1.3 | AI capability test table and a one-page reflection |
| 2 | AI and Machine Learning in Africa | Tasks C2.1 to C2.3 | Data audit and a problem brief |
| 3 | Python for AI | Tasks C3.1 to C3.5 and the notes’ Workshop 1 | Notebook with all tests passing |
| 4 | Mathematical Foundations of ML | Tasks C4.1 to C4.5 | Notebook with worked answers |
| 5 | Machine Learning Essentials | Tasks C5.1 to C5.3 and Workshop 3 | Model comparison report |
| 6 | Applied Generative AI | Tasks C6.1 to C6.4, Workshop 5 and the capstone | Published demo and portfolio entry |
Part P2: Tool kit
Free tiers and licenses change, so check each tool’s current terms. Prefer free tools and open-source libraries when you can.
Coding and notebooks
| Tool | Best for | Notes |
|---|---|---|
| Google Colab | Running Python in the browser, free GPU time with limits | Needs internet; save work to Drive or GitHub |
| Jupyter Notebook or JupyterLab | Local notebooks, offline work | Install with Anaconda or pip install jupyterlab |
| Kaggle Notebooks | Notebooks with datasets and competitions | Free accounts; weekly GPU quota |
| VS Code | Larger projects, scripts, debugging | Add the Python and Jupyter extensions |
| Git and GitHub | Version control and portfolio | Learn commit, push, branches, README |
Data and visualization
| Tool | Best for |
|---|---|
| pandas, NumPy, SciPy | Data handling, math and statistics |
| SQLite with DB Browser, or DuckDB | Practicing SQL on a laptop without a server |
| Matplotlib, Seaborn, Plotly | Charts in Python |
| Power BI Desktop (Windows) and Tableau Public | Dashboards |
| Google Looker Studio | Free browser-based dashboards from sheets and files |
| OpenRefine | Cleaning messy tables with a visual tool |
| Excel or Google Sheets | Quick checks and sharing results |
Machine learning and deep learning
| Tool | Best for |
|---|---|
| scikit-learn | Classical ML, pipelines, evaluation |
| XGBoost or LightGBM | Strong gradient boosting on tabular data |
| TensorFlow and Keras, or PyTorch | Neural networks and deep learning |
| statsmodels | Statistical models with detailed summaries |
| Optuna or scikit-learn search tools | Hyperparameter tuning |
| SHAP | Explaining model predictions |
Big data and generative AI
| Tool | Best for |
|---|---|
| PySpark | Distributed data processing practice (local mode in Colab) |
| Hugging Face (Transformers, Datasets, Hub) | Pre-trained models and open datasets |
| sentence-transformers | Embeddings for search and RAG |
| Ollama or similar local runners | Running small open models on your own computer |
| An approved AI assistant | Drafting, explaining, debugging, under your institution’s rules |
| Vector stores such as FAISS or Chroma | Retrieval for RAG |
Deployment and sharing
| Tool | Best for |
|---|---|
| joblib or pickle | Saving trained models |
| FastAPI or Flask | Serving a model as an API |
| Streamlit or Gradio | Quick web demos of models |
| Streamlit Community Cloud or Hugging Face Spaces | Free hosting for small demos |
| Docker | Packaging an application to run anywhere |
| GitHub Pages | Publishing reports and notes |
Data sources for practice
| Source | Use |
|---|---|
| National Institute of Statistics of Rwanda (NISR) | National statistics and surveys |
| World Bank Open Data, WHO and FAO portals | Indicators with APIs |
| Kaggle Datasets and Zindi competitions | Practice datasets, many African |
| Hugging Face Datasets | Text, speech and image data, including African languages |
| Built-in scikit-learn datasets | Offline practice with no download |
| Mozilla Common Voice and Masakhane resources | Speech and text for African languages |
Low-connectivity tips
- Install Anaconda while you have good internet, and work offline afterwards.
- Download datasets and library files in advance.
- Use small samples while developing, and run the full data only when ready.
- Save checkpoints and keep a copy of work on a USB drive.
Part P3: Practice tasks with guidance
Each task lists the time, tools, what to do, how to know you succeeded, and a hint.
Course 1: Artificial Intelligence: Past, Present and Future
| Task | What to do | Tools | Success check |
|---|---|---|---|
| C1.1 Capability test (60 min) | Give an approved AI assistant 10 varied tasks (summarize, translate to Kinyarwanda, do arithmetic, explain a chart, write code, answer a local fact question). Record the prompt, the result, and whether it was correct. | AI assistant, spreadsheet | A table showing at least two clear failures and why they happened |
| C1.2 Timeline poster (60 min) | Choose five milestones from Module S1 and make a one-page timeline with one sentence on why each mattered. | Canva, PowerPoint or Docs | Dates are checked against reliable sources |
| C1.3 Pros and cons debate (45 min) | In pairs, argue for and against using AI for one decision (such as loan approval), then swap sides. | Notes | A list of three benefits, three risks and one safeguard |
Guidance: verify every date and fact against a reliable source, and note that AI tools can be confidently wrong.
Course 2: AI and Machine Learning in Africa
| Task | What to do | Tools | Success check |
|---|---|---|---|
| C2.1 Local problem scan (60 min) | List five problems in your community that data could help with. Score each on impact, data availability and feasibility from 1 to 5. | Spreadsheet | One problem chosen with a written reason |
| C2.2 Data audit (90 min) | Pick a public dataset about an African country. Report rows, columns, missing values, time period, source, license and who is possibly missing from the data. | pandas, Colab | A one-page audit with at least three data quality issues and two representation concerns |
| C2.3 Solution brief (60 min) | Fill in the design canvas from Module S4 for the chosen problem, including deployment for weak connectivity. | Docs | The brief states users, decision, metrics, deployment and risks |
Guidance: start with the user, not the algorithm. A simple rule or dashboard may beat a complex model.
Course 3: Python for AI
Open a notebook and complete each problem so that the tests pass. Try them before reading the hints.
# C3.1 Min-max normalization: map values to the range 0 to 1
def normalize(values):
...
# C3.2 Word frequency: lowercase words, ignore punctuation
def word_freq(text):
...
# C3.3 Moving average with window k (return one value per full window)
def moving_average(values, k):
...
# C3.4 Accuracy: share of predictions equal to the true labels
def accuracy(y_true, y_pred):
...
# C3.5 The k keys with the highest values, highest first
def top_k(d, k):
...
# ---- self-check tests ----
assert normalize([2, 4, 6]) == [0.0, 0.5, 1.0]
assert word_freq("The cat, the dog.") == {"the": 2, "cat": 1, "dog": 1}
assert moving_average([1, 2, 3, 4], 2) == [1.5, 2.5, 3.5]
assert accuracy([1, 0, 1, 1], [1, 0, 0, 1]) == 0.75
assert top_k({"a": 3, "b": 9, "c": 5}, 2) == ["b", "c"]
print("All tests passed")
| Problem | Hint |
|---|---|
| C3.1 | for each value |
| C3.2 | Use str.lower, remove punctuation with
str.strip or re.findall(r"[a-z]+", ...), count
with a dictionary or collections.Counter |
| C3.3 | A loop over range(len(values) - k + 1) and
sum(values[i:i+k]) / k |
| C3.4 | sum(a == b for a, b in zip(...)) / len(y_true) |
| C3.5 | sorted(d, key=d.get, reverse=True)[:k] |
Then repeat the Week 1 practical workshop (data cleaning) without looking at the solution.
Course 4: Mathematical Foundations of Machine Learning
Solve by hand first, then verify with NumPy. Expected answers are in the table.
| Task | Problem | Verify with | Expected |
|---|---|---|---|
| C4.1 | Cosine similarity of and | np.dot(a,b)/(np.linalg.norm(a)*np.linalg.norm(b)) |
about 0.9746 |
| C4.2 | Solve and | np.linalg.solve([[2,1],[1,3]], [8,13]) |
, |
| C4.3 | Minimize with gradient descent from | Loop: x -= 0.1*(2*x-4) |
near 2 |
| C4.4 | Expected value and variance of a fair die | np.mean, np.var on 1 to 6 |
3.5 and 2.9167 |
| C4.5 | A disease has 1% prevalence; a test finds 95% of cases and wrongly flags 5% of healthy people. Chance a positive is correct? | Bayes’ theorem | about 0.16 |
Guidance: if a result does not match, check shapes
(a.shape) and whether you divided by the right
quantity.
Course 5: Machine Learning Essentials
C5.1: model comparison harness (90 min). This runs offline with a built-in dataset.
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
from sklearn.metrics import roc_auc_score, recall_score, precision_score
X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
models = {
"Baseline": DummyClassifier(strategy="most_frequent"),
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"Decision tree": DecisionTreeClassifier(max_depth=4, random_state=0),
"Random forest": RandomForestClassifier(n_estimators=200, random_state=0),
}
rows = []
for name, m in models.items():
cv = cross_val_score(m, Xtr, ytr, cv=5, scoring="roc_auc").mean()
m.fit(Xtr, ytr)
p = m.predict(Xte)
rows.append({"model": name, "cv_auc": cv,
"test_auc": roc_auc_score(yte, m.predict_proba(Xte)[:, 1]),
"precision": precision_score(yte, p), "recall": recall_score(yte, p)})
print(pd.DataFrame(rows).round(3).to_string(index=False))
Typical results (yours may differ slightly): the baseline has AUC 0.50; logistic regression about 0.998 test AUC; random forest about 0.994; the shallow tree about 0.943. A simple, scaled linear model often wins on clean tabular data like this, so always try it.
| Task | What to do | Success check |
|---|---|---|
| C5.1 | Run the harness, then add one more model (for example gradient boosting) and one more metric | Table with at least five columns; baseline AUC near 0.50 |
| C5.2 Error analysis (60 min) | List the misclassified test rows and look for patterns | A short note on where the best model fails |
| C5.3 Mini competition (2 hours) | Pick a beginner competition or dataset on Kaggle or Zindi; build a baseline, then improve with feature work and tuning; keep a log of experiments | A submission file, an experiment log and a README |
Guidance for competitions: build the simplest baseline in the first hour, record every change and its validation score, never tune on the test set, and read the discussion forum for ideas.
Course 6: Applied Generative AI
| Task | What to do | Tools | Success check |
|---|---|---|---|
| C6.1 Prompt library (60 min) | Write 10 reusable prompts for your field using the pattern table in Week 4, and test each on three inputs | AI assistant | Each prompt has a purpose, template, example and known weaknesses |
| C6.2 RAG assistant (3 hours) | Build the Module S5 RAG example over 10 to 20 short documents from your institution (non-sensitive). Add a Gradio or Streamlit interface. | scikit-learn or sentence-transformers, Gradio or Streamlit | Answers cite the source passage; says “not found” when the answer is absent |
| C6.3 Evaluation set (90 min) | Write 25 questions with reference answers (include 5 trick questions not in the documents). Score the assistant on accuracy, faithfulness and safety. | Spreadsheet | A score table and a list of top three failures with fixes |
| C6.4 Safety review (60 min) | Test for privacy leaks, biased answers and harmful requests; write mitigations | Checklist from Week 4, Session 4 | A one-page risk note |
A minimal interface sketch for C6.2 (run in Colab after
pip install gradio):
import gradio as gr
def answer(question):
context = retrieve(question) # from the Module S5 example
return "Retrieved passages:\n\n" + "\n\n".join(context)
gr.Interface(fn=answer, inputs="text", outputs="text",
title="Policy help desk (demo)").launch()
Part P4: Build your portfolio
A portfolio shows employers what you can do. Keep three to five strong projects.
| Element | What to include |
|---|---|
| Repository | One GitHub repository per project with a clear name |
| README | Problem, data source and license, method, results, how to run, limits |
| Notebook | Runs from top to bottom; short explanations between code cells |
| Results | Honest metrics, a baseline, and one or two clear charts |
| Demo | A Streamlit, Gradio or dashboard link, if possible |
| Responsible AI note | Privacy, bias and limitation notes |
| Short write-up | A one-page summary for non-technical readers |
Suggested portfolio projects: the Week 1 cleaning workshop, the Week 2 agriculture dashboard, the Week 3 loan model with cost analysis, the Module S5 RAG assistant, and the capstone.
README template
# Project title
One sentence: what problem does this solve and for whom?
## Data
Source, license, size, time period, known limits.
## Method
Cleaning, features, models compared, validation approach.
## Results
Table of metrics against the baseline; one chart.
## How to run
Steps to reproduce (Colab link, requirements).
## Limits and responsible use
Bias, privacy, where the model should not be used.
Part P5: Troubleshooting and good habits
| Problem | Likely cause | What to try |
|---|---|---|
ModuleNotFoundError |
Library not installed | pip install name in a cell, then restart the
runtime |
KeyError on a column |
Misspelled or hidden spaces in the name | Print df.columns; use
df.columns.str.strip() |
| Shapes do not match | Wrong dimension for a model or matrix | Print .shape of every array |
| Model scores too good to be true | Data leakage | Split first; fit scalers only on training data; check for target-like columns |
| Training is slow | Too much data or too complex a model | Sample the data, simplify, use a GPU runtime only if needed |
| Out of memory | Large data in pandas | Use fewer columns, smaller data types, or Parquet and Spark |
| Results change every run | No random seed | Set random_state or
np.random.default_rng(seed) |
| Notebook works only on your machine | Hidden state or paths | Restart and run all; list library versions in a README |
| An AI assistant gives wrong code | It guessed | Run small tests, read the error, and consult the official documentation |
Good habits checklist
Appendix A: Quick Reference Sheets
A1. Python essentials
| Task | Code |
|---|---|
| Print and format | print(f"{x:.2f}") |
| Type conversion | int("5"), float("2.5"),
str(10) |
| List operations | a.append(x), a[1:3], len(a),
sorted(a) |
| Dictionary | d["key"], d.get("key", 0),
d.items(), d.keys() |
| Conditions | if x > 0: ... elif x == 0: ... else: ... |
| Loops | for i in range(5):, for item in items:,
while cond: |
| Comprehension | [x**2 for x in a if x > 0] |
| Function | def f(x, y=1): return x + y |
| Import | import pandas as pd,
from math import sqrt |
| Handle errors | try: ... except ValueError: ... |
| Read a text file | with open("f.txt") as f: text = f.read() |
A2. pandas essentials
| Task | Code |
|---|---|
| Read data | pd.read_csv("f.csv"),
pd.read_excel("f.xlsx") |
| First look | df.head(), df.info(),
df.describe(), df.shape |
| Select columns | df["a"], df[["a", "b"]] |
| Select rows | df.loc[label], df.iloc[position],
df[df["a"] > 5] |
| New column | df["c"] = df["a"] / df["b"] |
| Sort | df.sort_values("a", ascending=False) |
| Missing values | df.isna().sum(), df.fillna(0),
df.dropna() |
| Duplicates | df.drop_duplicates() |
| Change type | df["a"].astype(int),
pd.to_datetime(df["d"]) |
| Text cleaning | df["s"].str.strip().str.lower() |
| Group | df.groupby("g")["a"].agg(["mean", "count"]) |
| Pivot | df.pivot_table(index="g", columns="h", values="a", aggfunc="mean") |
| Merge | df1.merge(df2, on="key", how="left") |
| Stack tables | pd.concat([df1, df2]) |
| Dummy variables | pd.get_dummies(df, columns=["cat"]) |
| Save | df.to_csv("out.csv", index=False) |
A3. Visualization essentials
| Question | Seaborn or Matplotlib call |
|---|---|
| Distribution | sns.histplot(data=df, x="a", kde=True) |
| Compare groups | sns.boxplot(data=df, x="g", y="a") |
| Relationship | sns.scatterplot(data=df, x="a", y="b", hue="g") |
| Trend over time | plt.plot(dates, values) |
| Category totals | sns.barplot(data=df, x="g", y="a") |
| Correlations | sns.heatmap(df.corr(numeric_only=True), annot=True) |
| Many pairs | sns.pairplot(df) |
| Labels and save | plt.title(...), plt.xlabel(...),
plt.savefig("c.png", dpi=200) |
A4. SQL essentials
SELECT col1, AGG(col2) AS name -- choose columns
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id -- combine tables
WHERE condition -- filter rows
GROUP BY col1 -- make groups
HAVING AGG(col2) > 10 -- filter groups
ORDER BY name DESC -- sort
LIMIT 20; -- limit rows
| Idea | Example |
|---|---|
| Count rows | COUNT(*) |
| Distinct values | COUNT(DISTINCT col) |
| Conditional logic | CASE WHEN a > 5 THEN 'high' ELSE 'low' END |
| Missing values | WHERE col IS NULL, COALESCE(col, 0) |
| Named steps | WITH step AS (SELECT ...) SELECT * FROM step |
| Running total | SUM(x) OVER (PARTITION BY g ORDER BY d) |
| Rank | RANK() OVER (PARTITION BY g ORDER BY x DESC) |
Appendix B: Choosing and Evaluating Models
B1. Which method for which problem?
| Problem | Typical methods | Metrics |
|---|---|---|
| Predict a number | Linear regression, random forest, gradient boosting | MAE, RMSE, R squared |
| Predict a category | Logistic regression, random forest, gradient boosting, neural network | Accuracy, precision, recall, F1, AUC |
| Find groups | k-means, hierarchical, DBSCAN | Silhouette score, usefulness |
| Reduce dimensions | PCA | Variance explained |
| Find unusual cases | Isolation forest | Review of flagged cases |
| Forecast over time | Moving averages, ARIMA, gradient boosting with date features | MAE, RMSE on future periods |
| Work with text or images | Pre-trained transformers or CNNs | Task-specific metrics |
B2. Model-building checklist
- State the problem and how the prediction will be used.
- Split the data (by time if the problem is about the future).
- Build a baseline: the average, or a simple rule, or logistic regression.
- Add complexity only if it improves validation results.
- Use cross-validation and a pipeline to avoid leakage.
- Check performance by subgroup (fairness).
- Test once on the held-out test set.
- Document, deploy carefully and monitor.
B3. Key formulas
| Name | Formula |
|---|---|
| Mean | |
| Sample standard deviation | |
| Z-score | |
| Pearson correlation | |
| Linear model | |
| Mean squared error | |
| R squared | |
| Sigmoid | |
| Precision | |
| Recall | |
| F1 |
B4. Common mistakes and how to avoid them
| Mistake | Why it hurts | Fix |
|---|---|---|
| Testing on training data | Results are too optimistic | Hold out a test set |
| Scaling before splitting | Information leaks from the test set | Use a pipeline |
| Using accuracy on rare events | A useless model can look excellent | Use precision, recall, AUC |
| Deleting outliers automatically | You may delete the most important cases | Investigate first |
| Treating correlation as cause | Wrong decisions | Think about confounders and experiments |
| No baseline | You cannot tell if the model is worth it | Always compare to a simple baseline |
| Ignoring subgroups | Hidden unfairness | Evaluate by group |
| Ignoring the cost of errors | The metric does not match the real goal | Choose metrics and thresholds by cost |
Appendix C: Glossary
| Term | Meaning |
|---|---|
| Accuracy | Share of predictions that are correct |
| Algorithm | A set of steps for solving a problem |
| API | A way for programs to request data or services from each other |
| Artificial intelligence | Computer systems that perform tasks needing human-like intelligence |
| AUC | Area under the ROC curve; how well a model ranks positives above negatives |
| Backpropagation | Method for computing how to adjust network weights during training |
| Bias (statistical) | Systematic error; in AI ethics, unfair treatment of groups |
| Big data | Data too large, fast or varied for traditional tools |
| Classification | Predicting a category |
| Clustering | Grouping similar items without labels |
| Confusion matrix | Table of correct and incorrect predictions by class |
| Context window | The amount of text an LLM can consider at once |
| Correlation | A measure of how two variables move together |
| Cross-validation | Evaluating a model on several train and validation splits |
| Dashboard | An interactive screen of key numbers and charts |
| Data lake | Cheap storage for raw data of all types |
| Data leakage | Test information accidentally used in training |
| Data warehouse | A structured store optimized for analysis |
| DataFrame | A table of data with named columns |
| Deep learning | Machine learning with many-layered neural networks |
| Dropout | Randomly switching off neurons during training to prevent overfitting |
| EDA | Exploratory data analysis |
| Embedding | A numeric vector representing the meaning of a word or item |
| Epoch | One pass through the whole training dataset |
| ETL | Extract, transform, load: moving and preparing data |
| Feature | An input variable used by a model |
| Feature engineering | Creating or transforming features to help a model |
| Fine-tuning | Further training a pre-trained model on specific data |
| Generative AI | AI that creates new text, images, audio or code |
| Gradient descent | Repeatedly adjusting parameters to reduce the loss |
| Hallucination | A confident but false output from a generative model |
| HDFS | Hadoop Distributed File System |
| Hyperparameter | A setting chosen before training |
| Imputation | Filling in missing values |
| IQR | Interquartile range, Q3 minus Q1 |
| JSON | A text format for nested data |
| k-means | A clustering algorithm using k centers |
| Label | The correct answer for an example (the target) |
| LLM | Large language model |
| Loss function | A measure of how wrong a model’s predictions are |
| Machine learning | Systems that learn patterns from data |
| MAE, RMSE | Common error measures for regression |
| Median | The middle value |
| Model card | A short document describing a model’s purpose, data and limits |
| Neural network | A model built from layers of connected neurons |
| Normal distribution | The bell-shaped distribution |
| Outlier | A value far from the others |
| Overfitting | Fitting noise so the model fails on new data |
| Parquet | A compressed, column-based file format for big data |
| PCA | Principal component analysis, for reducing dimensions |
| Pipeline | A chain of processing and modeling steps applied consistently |
| Precision | Of the cases predicted positive, the share that really are |
| Prompt | The instruction given to a generative model |
| p-value | Probability of a result at least as extreme as observed if the null hypothesis is true |
| RAG | Retrieval-augmented generation: giving an LLM retrieved documents to answer from |
| Recall | Of the real positives, the share the model found |
| Regression | Predicting a number |
| Regularization | Techniques that discourage overly complex models |
| Reinforcement learning | Learning through rewards from actions |
| Silhouette score | A measure of how well points fit their clusters |
| Spark | A fast engine for distributed data processing |
| Standard deviation | A measure of spread around the mean |
| Supervised learning | Learning from labeled examples |
| Test set | Data held back for the final evaluation |
| Token | A piece of text processed by a language model |
| Training set | Data used to fit the model |
| Transformer | A neural network architecture based on attention |
| Underfitting | A model too simple to capture real patterns |
| Unsupervised learning | Finding structure in unlabeled data |
| Validation set | Data used to choose and tune models |
| Variance | Spread of values; in ML, sensitivity of a model to the training data |
Appendix D: Hints and Answers to Selected Exercises
These hints help you check your thinking. Try each exercise yourself first.
Week 1, Session 2: a BMI function is
weight_kg / height_m ** 2. For a list scores,
the mean is sum(scores) / len(scores), and max
and min give the extremes.
Week 1, Session 3: use
df.groupby("class")["score"].mean() for the class averages.
To filter above the class average, use
df["score"] > df.groupby("class")["score"].transform("mean").
Week 2, Session 1: for 12, 15, 11, 14, 90 the mean is 28.4 and the median is 14. The value 90 pulls the mean far above the typical values, so the median is the better summary.
Week 2, Session 2: with 10,000 people, 1% sick means 100 sick and 9,900 healthy. A 95% accurate test finds 95 of the sick and wrongly flags 5% of the healthy (495). So only 95 of 590 positive results are real: about 16%.
Week 3, Session 2: with TP=40, FP=10, FN=20, TN=130: precision is 40 / 50 = 0.80, recall is 40 / 60 = 0.67, and F1 is about 0.73. Accuracy is 170 / 200 = 0.85.
Week 3, Session 3: you should see the training score of an unrestricted tree near perfect while the test score is clearly lower. That gap is overfitting.
Week 4, Session 4: a typical proxy variable is a postal code or school name that is closely linked to ethnicity, income or gender. Removing the sensitive column does not remove the effect.
Module S3 (Bayes): , so only about one positive result in three is a true case.
Appendix E: Resources and Open Data
Data sources
| Source | What you can find |
|---|---|
| National Institute of Statistics of Rwanda (NISR) | Census, household surveys and national statistics |
| World Bank Open Data | Country indicators with an API |
| DHS Program | Demographic and health surveys (registration required) |
| Kaggle Datasets | Thousands of datasets across topics |
| UN, WHO and FAO data portals | Health, agriculture and development data |
| Open data portals of African governments and cities | Local administrative data |
Always read each dataset’s license and terms before using or sharing it.
Free learning resources
- Official documentation for Python, pandas, scikit-learn and Apache Spark.
- An Introduction to Statistical Learning with Python by James, Witten, Hastie, Tibshirani and Taylor (free online).
- Python for Data Analysis by Wes McKinney.
- Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow by Aurelien Geron.
- Learning Spark (2nd edition) by Damji, Wenig, Das and Lee.
- Kaggle Learn micro-courses on Python, pandas, SQL, visualization and machine learning.
Tools used in this course
| Tool | Use |
|---|---|
| Google Colab | Free notebooks in the browser |
| Python 3 with NumPy, pandas, SciPy | Data handling and statistics |
| Matplotlib, Seaborn, Plotly | Visualization |
| scikit-learn | Classical machine learning |
| TensorFlow and Keras | Neural networks |
| PySpark | Distributed data processing |
| SQLite and SQL | Querying data |
| Power BI or Tableau | Dashboards |
| An approved AI assistant | Prompt practice and coding help |
Final note
Data and AI skills grow with practice. Use these notes as a map, not a destination: build things, make mistakes, ask for help, and share what you learn. Use data and AI to serve people, and respect the people behind the data.
Appendix F: Templates
F1. Capstone project brief
Copy this template into your notebook or a document and fill it in before you start coding.
| Field | Your answer |
|---|---|
| Team members and roles | |
| Problem statement (one sentence) | |
| Who will use the result, and for what decision? | |
| Data source(s) and license | |
| Permission and privacy check (any personal data?) | |
| Target variable and type (number, category, none) | |
| Baseline to beat | |
| Metrics and why they fit the problem | |
| Main risks (bias, privacy, data quality) | |
| Success looks like |
F2. Data dictionary
A data dictionary describes every column, so others can understand and reuse your dataset.
| Column | Type | Meaning and unit | Allowed values or range | Missing means |
|---|---|---|---|---|
district |
text | District of the record | 30 official district names | Not reported |
rainfall_mm |
number | Total rainfall in the season, in millimetres | 0 to 3,000 | Station offline |
yield_t |
number | Harvest in tonnes per hectare | 0 to 15 | Not harvested |
F3. Model card
| Section | What to write |
|---|---|
| Model name and version | |
| Purpose and intended users | |
| Out-of-scope uses | |
| Training data (source, period, size) | |
| Evaluation data and metrics | |
| Performance overall and by group | |
| Known limits and risks | |
| Privacy and security notes | |
| Human oversight and appeal process | |
| Contact and date |
F4. Weekly self-assessment checklist
Tick each item when you can do it without looking at the notes.
Week 1
Week 2
Week 3
Week 4
Appendix G: Self-Test Questions
Answer each question before looking at the answer key. Each week has eight questions.
Week 1 questions
| # | Question |
|---|---|
| 1 | Which term describes systems that learn patterns from data without explicit rules: AI, machine learning or deep learning? |
| 2 | Name the five Vs of big data. |
| 3 | What does df.iloc[0:2] return? |
| 4 | Which Python collection stores unique values only? |
| 5 | In a merge, which how= keeps all rows from the left
table? |
| 6 | Why should you keep an untouched copy of raw data? |
| 7 | What does the IQR rule flag as an outlier? |
| 8 | Give one situation where filling missing values with the median is better than with the mean. |
Week 2 questions
| # | Question |
|---|---|
| 1 | Five incomes are 80, 90, 100, 110 and 1,500. Which is a better “typical” value, the mean or the median? |
| 2 | What does a correlation of -0.8 tell you, and what does it not tell you? |
| 3 | What does a p-value of 0.03 mean? |
| 4 | Which distribution suits the number of calls arriving at a help line per hour? |
| 5 | Why should bar charts start at zero? |
| 6 | What is Simpson’s paradox? |
| 7 | Name three principles of a good dashboard. |
| 8 | Which test compares the means of three or more groups? |
Week 3 questions
| # | Question |
|---|---|
| 1 | Why do we hold out a test set? |
| 2 | A test finds 90% of sick patients and wrongly flags 5% of healthy ones. Which of these numbers is the recall? |
| 3 | Why is 99% accuracy not impressive for fraud detection when 1% of cases are fraud? |
| 4 | What is data leakage, and how does a pipeline help prevent it? |
| 5 | How does a random forest reduce the overfitting of a single tree? |
| 6 | Why should features be standardized before k-means? |
| 7 | What does PCA do? |
| 8 | What does it mean if validation loss rises while training loss keeps falling? |
Week 4 questions
| # | Question |
|---|---|
| 1 | What does lazy evaluation mean in Spark? |
| 2 | What is the difference between a data warehouse and a data lake? |
| 3 | What is the difference between WHERE and
HAVING? |
| 4 | Why can a language model “hallucinate”? |
| 5 | Name three parts of a strong prompt. |
| 6 | Give two sources of bias in AI systems. |
| 7 | What is data minimization? |
| 8 | Why do we need human oversight of automated decisions? |
Answer key
| Week | Answers |
|---|---|
| Week 1 | 1. Machine learning. 2. Volume, velocity, variety, veracity, value.
3. The first two rows (positions 0 and 1). 4. A set. 5.
left. 6. So that mistakes can be corrected and your work
can be reproduced. 7. Values below Q1 – 1.5 x IQR or above Q3 + 1.5 x
IQR. 8. When the data is skewed or has extreme values, such as
incomes. |
| Week 2 | 1. The median (100), because the extreme 1,500 pulls the mean up to 376. 2. A strong negative linear relationship; it does not show that one variable causes the other. 3. If there were no real effect, a result at least this extreme would occur about 3% of the time; it is not the probability that the hypothesis is true. 4. Poisson. 5. A truncated axis exaggerates differences and misleads. 6. A trend in the combined data that reverses within each group. 7. Know the audience, key numbers first, simplicity, consistent colors, clear filters, verified numbers (any three). 8. One-way ANOVA. |
| Week 3 | 1. To estimate performance on new, unseen data honestly. 2. 90% (the share of sick patients found). 3. A model that always says “not fraud” gets 99% and finds nothing; use precision, recall and AUC. 4. Information from the test set influencing training; a pipeline fits scalers and other steps only on training data. 5. It averages many trees trained on random subsets, which cancels much of their individual noise. 6. k-means uses distances, so features with large ranges would dominate. 7. It builds a few new axes that capture most of the variation, for visualization and noise reduction. 8. The model is overfitting; use early stopping or regularization. |
| Week 4 | 1. Spark records transformations and runs them only when an action
asks for a result, so it can plan efficiently. 2. A warehouse stores
cleaned, structured data for analysis; a lake stores raw data of all
types cheaply. 3. WHERE filters rows before grouping;
HAVING filters groups after aggregation. 4. It predicts
likely text rather than checking facts, so it can produce fluent but
false statements. 5. Role or context, task, input data, constraints,
output format, examples (any three). 6. Historical, sampling,
measurement, label, representation, deployment bias, proxy variables
(any two). 7. Collect and keep only the data you really need. 8. People
must be able to review, challenge and correct automated decisions that
affect others. |







