Problem Set 3 — Advanced Data Analytics¶

HEC Lausanne, autumn 2026 · Topics: k-nearest neighbours, naive Bayes, decision trees, the perceptron

Based on course materials by Prof. Simon Scheidegger.

How to work through this notebook. Cells marked TODO are yours to complete — code cells contain ... where your code goes, markdown cells say (your answer here). Everything runs top to bottom with no internet access and no absolute paths; the data ships in data/. When you are done, Kernel → Restart & Run All must execute cleanly to the end.

Nothing is submitted. These problem sets are practice; the solution is discussed in the exercise session. Because nobody grades them, the notebook has to tell you whether you got it right — that is what the "Certify it" parts are for: checks you run on your own code, with the expected outcome stated so you can see for yourself.

AI assistants. You may — and realistically will — work with an AI assistant (ChatGPT, Claude, Copilot). That is fine. Assistants are very good at producing code that runs and looks right; the skill that will carry your project is telling whether it is right. Treat every "Certify it" part as the question you should be asking the assistant's code — and your own.

A word on this set in particular. Four of the five exercises ask you to code a classifier by hand and then check it against scikit-learn. That is the point: the library version is three lines, so the only way to find out whether you understand the algorithm is to write it yourself and have the library disagree with you.

In [ ]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)

Exercise 1 — k-nearest neighbours, by hand¶

A shop has recorded, for ten customers, their age, sex, annual sales, and the channel through which they are best reached:

Age m/f Sales Channel
20 f 10 E-mail
30 m 90 Phone
40 m 70 Post
60 f 100 Phone
20 m 30 E-mail
30 f 40 E-mail
70 m 80 Post
20 f 110 Phone
60 m 80 Post
40 f 20 E-mail

Two new customers arrive and we want to know which channel to use:

Age m/f Sales Channel
30 m 50 ?
90 f 100 ?

Code the algorithm up yourself — no KNeighborsClassifier until part (c), where you use it only as a reference.

(a) Encode and normalise¶

Encode the non-numerical feature so it can enter a distance computation, and standardise the numeric columns: subtract the mean, divide by the standard deviation. Fit mean and standard deviation on the training rows only and apply the very same numbers to the two query customers.

Why normalise at all? Sales ranges over 100 units and m/f over 1. In a raw Euclidean distance the sales column would decide every neighbourhood on its own and the sex of the customer would be worth about one hundredth of a franc of turnover.

In [ ]:
customers = pd.DataFrame(
    {
        "Age": [20, 30, 40, 60, 20, 30, 70, 20, 60, 40],
        "Sex": ["f", "m", "m", "f", "m", "f", "m", "f", "m", "f"],
        "Sales": [10, 90, 70, 100, 30, 40, 80, 110, 80, 20],
        "Channel": [
            "E-mail", "Phone", "Post", "Phone", "E-mail",
            "E-mail", "Post", "Phone", "Post", "E-mail",
        ],
    }
)

queries = pd.DataFrame({"Age": [30, 90], "Sex": ["m", "f"], "Sales": [50, 100]})

FEATURES = ["Age", "male", "Sales"]

# TODO: add a numeric column `male` (1 for "m", 0 for "f") to both frames,
# build X (the training features) and y (the Channel labels), then
# standardise: mu = X.mean(), sigma = X.std() -- fit on the training rows,
# apply to both. Call the results Z (training) and Zq (queries).
...

(b) The vote¶

Implement k-nearest neighbours with $k = 3$ and the Euclidean distance: for a query $q$, compute $d_i = \lVert z_i - z_q\rVert_2$ for every training row, keep the three smallest, and take the majority vote of their labels. Print the three neighbours with their distances and the resulting prediction for both new customers.

You will find that one of the two queries does not have a majority. Do not patch that away — part (c) is about it.

In [ ]:
def knn_predict(zq, Z, y, k=3):
    # TODO: Euclidean distances from zq to every row of Z, the k smallest,
    # and the majority vote of their labels. Return the prediction and the
    # table of neighbours (label + distance) so you can look at it.
    ...


# TODO: run it for both queries and print the neighbours and the prediction.
...

TODO (your answer here: what does k = 3 predict for each of the two customers?)

(c) Certify it¶

Three checks, and one question that has no code answer.

C1 — the scaler. sklearn.preprocessing.StandardScaler divides by the population standard deviation ($\text{ddof}=0$), pandas' .std() by the sample one ($\text{ddof}=1$). Standardise with both and assert that the two differ by the same constant factor $\sqrt{n/(n-1)}$ in every column. Because it is the same factor everywhere, it rescales all distances alike and leaves the neighbour ranking untouched — but it does change the printed distances, and it is exactly the kind of silent convention difference that makes your numbers disagree with a classmate's.

C2 — the distances. Fit KNeighborsClassifier(n_neighbors=3).fit(Z, y) and compare its kneighbors() output with yours: assert the distance vectors agree to 1e-12.

C3 — the tie. Print the two smallest distances for customer 1 with 17 significant digits and assert that they are bit-identical. Then find out, from the documentation or by experiment, what KNeighborsClassifier.predict returns for that customer, and why — and write down whether you would ship that answer to the marketing department.

In [ ]:
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

# TODO C1: standardise with StandardScaler, compare with your Z, and assert
# the ratio is sqrt((n - 1) / n).
...

# TODO C2: fit KNeighborsClassifier(n_neighbors=3) on (Z, y), call
# kneighbors(Zq) and assert the distances match yours to 1e-12.
...

# TODO C3: print the two smallest distances for query 1 with `repr` (all
# digits) and assert they are exactly equal. Then print what
# KNeighborsClassifier predicts for both queries.
...

TODO (what does KNeighborsClassifier return for customer 1, why, and would you ship it?)

Exercise 2 — Naive Bayes, by hand¶

Six newspaper articles, each a bag of words with a category:

Document Content Category
d1 ball goal cart goal Sports
d2 theater cart drama Culture
d3 drama strategy decision drama Politics
d4 theater ball Culture
d5 ball goal player strategy Sports
d6 theater cart opera Culture

Code the algorithm up yourself. Part (d) checks it against sklearn.

(a) Bag of words¶

Build the document–term count matrix: one row per document, one column per distinct word, entry = how often the word occurs in the document. Keep the vocabulary sorted — a set has no order, and an algorithm whose output depends on iteration order is an algorithm whose output depends on the weather.

In [ ]:
docs = pd.DataFrame(
    {
        "Document": ["d1", "d2", "d3", "d4", "d5", "d6"],
        "Content": [
            "ball goal cart goal",
            "theater cart drama",
            "drama strategy decision drama",
            "theater ball",
            "ball goal player strategy",
            "theater cart opera",
        ],
        "Category": ["Sports", "Culture", "Politics", "Culture", "Sports", "Culture"],
    }
)

# TODO: build `vocab` (sorted list of distinct words) and `bow`, a DataFrame
# of counts indexed by Document with one column per word. Print it.
...

(b) The probabilities¶

Compute, from the six training documents:

  • the class priors $P[c]$ — the share of documents in each class;
  • the word likelihoods $P[w \mid c]$ with Laplace (add-one) smoothing:

$$P[w \mid c] = \frac{n_{w,c} + 1}{\left(\sum_{w'} n_{w',c}\right) + |V|}$$

where $n_{w,c}$ is how often word $w$ occurs in class $c$, and $|V|$ is the vocabulary size.

Why add one? Without it, player gets $P[\texttt{player} \mid \texttt{Culture}] = 0$, and a single unseen word annihilates the whole product for that class — one word vetoes all the others. Adding one to every count says "every word in the vocabulary could in principle appear in every class"; the denominator gains $|V|$ so the row still sums to one.

Print $P[c]$ and the full $P[w \mid c]$ table.

In [ ]:
# TODO: class priors P[c], class-level word counts, and the Laplace-smoothed
# P[w|c] table (rows = classes, columns = vocab). Print both, and assert
# each row of P[w|c] sums to 1.
...

(c) Classify d7 and d8¶

Document Content Category
d7 ball player strategy ?
d8 theater cart decision ?

Naive Bayes picks

$$\hat c = \arg\max_c \; P[c] \prod_{w \in d} P[w \mid c].$$

Work in log space: compute $\log P[c] + \sum_{w \in d} \log P[w \mid c]$ and take the argmax. Two reasons, and both matter beyond this toy:

  1. A product of a few hundred probabilities underflows to exactly 0.0 in double precision, and then argmax returns whichever class happens to come first. On three-word documents you get away with it; on the newspaper articles of Exercise 3 you do not.
  2. In log space a zero probability is $-\infty$ and shouts. In linear space it silently multiplies a class down to zero — or, if you "skip the zeros" to avoid that, silently rewards a class for never having seen the evidence.

Print, for each of d7 and d8, the log score of every class, the normalised posterior probabilities, and the prediction.

In [ ]:
tests = pd.DataFrame(
    {
        "Document": ["d7", "d8"],
        "Content": ["ball player strategy", "theater cart decision"],
    }
)

def nb_log_scores(text):
    # TODO: return a Series over `classes` with
    # log P[c] + sum_w log P[w|c], iterating over classes in sorted order.
    ...


# TODO: for each test document print the log scores, the normalised
# posteriors, and the argmax.
...

TODO (your answer here: the category of d7 and of d8, with the posteriors)

(d) Certify it¶

sklearn.naive_bayes.MultinomialNB(alpha=1) is, mathematically, exactly the algorithm you just wrote: multinomial likelihoods with add-one smoothing. Fit it on the same bag-of-words matrix and check three things, in increasing order of strength:

C1 — same predictions. Both must say Sports, Culture.

C2 — same likelihood table. np.exp(model.feature_log_prob_) must equal your $P[w \mid c]$ to 1e-12, with the rows in model.classes_ order (which is sorted — so it lines up with your classes if you sorted, and does not if you used a set).

C3 — same joint log scores. model.predict_joint_log_proba returns exactly $\log P[c] + \sum_w n_w \log P[w \mid c]$. Assert it matches your log scores to 1e-12. This is the strong check: two implementations can agree on the argmax by luck, but they do not agree on eight decimal places of the score by luck.

If C1 passes and C3 fails, you have a ranking-preserving bug — a dropped prior, a wrong denominator, a forgotten smoothing term. Those are the bugs that survive for years, because the answer still looks right.

In [ ]:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

# TODO: fit CountVectorizer(vocabulary=vocab) + MultinomialNB(alpha=1.0) on
# the six training documents, then run C1, C2 and C3.
...

Exercise 3 — Naive Bayes in practice: 20 Newsgroups¶

Multinomial naive Bayes is a workhorse of text classification. Here we use the 20 Newsgroups corpus, restricted to four groups:

comp.graphics, sci.space, soc.religion.christian, talk.religion.misc

The subsets ship with this notebook in data/newsgroups_train.csv and data/newsgroups_test.csv (columns text and label) — the same data sklearn.datasets.fetch_20newsgroups downloads, vendored so that the notebook runs offline and gives everyone the same split.

(a) Load and inspect¶

Load both files, print the number of documents per class in the training set, and print one document in full — you should look at what you are classifying at least once.

In [ ]:
# TODO: read data/newsgroups_train.csv and data/newsgroups_test.csv,
# report the sizes and the per-class counts, and print one training document.
...

(b) TF–IDF + multinomial naive Bayes¶

Raw word counts let long documents shout and let the word "the" outvote the word "orbit". TF–IDF rescales each count by how rare the word is across the corpus. Build the standard pipeline

make_pipeline(TfidfVectorizer(), MultinomialNB())

fit it on the training texts and labels, predict the test labels, and report the accuracy.

In [ ]:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score

# TODO: build the pipeline, fit on train["text"], train["label"], predict on
# test["text"], print the accuracy.
...

(c) The confusion matrix¶

Produce the confusion matrix of true against predicted labels — with the class names on the axes. An unlabelled 4×4 integer array is not a result; it is a puzzle, and the row/column order of sklearn.metrics.confusion_matrix is sorted(labels), not the order in which you happened to list the categories.

Use ConfusionMatrixDisplay (or a labelled heatmap) and then say, in the markdown cell, which pair of classes the model confuses and why that is not surprising.

In [ ]:
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# TODO: labelled confusion matrix, classes in sorted order.
...

TODO (which classes get confused, and why?)

(d) Classify an arbitrary string, and certify it¶

Write the utility that runs the fitted pipeline on a single string and returns the predicted category, then certify:

C1 — the split is clean. No test document may appear in the training set. assert that the intersection of the two text sets is empty. (An accuracy computed on documents the model has memorised is not an accuracy.)

C2 — beat the baseline. assert that the test accuracy exceeds 0.75; for comparison, always predicting the largest training class gives about 0.28.

C3 — the free-text example. assert that predict_category("determining the screen resolution") returns comp.graphics. The string contains none of the four category names — the model has to work from "screen" and "resolution" alone.

Then try two or three strings of your own, including one you expect it to get wrong.

In [ ]:
# TODO: predict_category(s) -> the label the pipeline assigns to a string.
...

# TODO C1: assert set(test.text) & set(train.text) == empty
# TODO C2: assert accuracy > 0.75
# TODO C3: assert predict_category("determining the screen resolution")
#          == "comp.graphics"
...

Exercise 4 — A decision tree by hand¶

Five movies. Roles is the number of distinct characters, Audiobook whether an accompanying audiobook exists:

Roles Duration [min] Audiobook Genre
5 80 no Action
15 120 yes Drama
15 100 yes Action
20 80 no Drama
5 80 no Action

Do not use an existing library for the tree itself — part (c) uses scikit-learn only as a reference.

(a) Grow the tree with information gain¶

The criterion is information gain, i.e. the reduction in Shannon entropy. For a set $S$ of rows with class shares $p_k$,

$$H(S) = -\sum_k p_k \log_2 p_k,$$

and a split of $S$ into $S_{\text{true}}, S_{\text{false}}$ has gain

$$\mathrm{IG} = H(S) - \frac{|S_{\text{true}}|}{|S|} H(S_{\text{true}}) - \frac{|S_{\text{false}}|}{|S|} H(S_{\text{false}}).$$

Implement:

  1. entropy(rows);
  2. best_split(rows) — try every feature column and every value occurring in it as a threshold (feature >= value), and return the split with the largest gain. Watch where you put the return: it belongs after the loop over the columns, not inside it. A return one indentation level too deep searches only the first feature and still produces a tree, a plausible-looking one, that is simply not the tree the criterion asks for.
  3. build_tree(rows) — recursive: stop when the best gain is 0 (the node is pure, or no split separates anything), otherwise split and recurse on both sides.

Print the gains of all candidate splits at the root, then print the tree.

In [ ]:
from collections import Counter

training_data = [
    [5, 80, 0, "Action"],
    [15, 120, 1, "Drama"],
    [15, 100, 1, "Action"],
    [20, 80, 0, "Drama"],
    [5, 80, 0, "Action"],
]
header = ["roles", "duration", "audiobook"]


def entropy(rows):
    # TODO: Shannon entropy in bits of the class labels (last column).
    ...


def partition(rows, col, value):
    # TODO: return (rows with row[col] >= value, the rest).
    ...


def best_split(rows):
    # TODO: loop over ALL columns and all values; return
    # (best_gain, best_col, best_value). Mind where the return goes.
    ...


def build_tree(rows):
    # TODO: recursive tree. A leaf is a Counter of the labels it holds.
    ...


# TODO: print the candidate gains at the root, build the tree, print it.
...

(b) Classify the two new movies¶

Roles Duration [min] Audiobook Genre
12 115 yes ?
2 180 yes ?

Walk each row down the tree and print the leaf it reaches, with the class counts in that leaf.

In [ ]:
testing_data = [[12, 115, 1], [2, 180, 1]]

def classify(row, node):
    # TODO: walk the tree until a Leaf; return its predictions.
    ...


# TODO: classify both test movies and print the leaf they land in.
...

(c) Certify it¶

DecisionTreeClassifier(criterion='entropy') implements the same criterion. Fit it on the same five rows and check:

C1 — the root split. Your root must induce the same partition of the five training rows as sklearn's. (The form differs: you split on feature >= value with a value from the data, sklearn on feature <= threshold with the midpoint between two observed values. Compare the two groups of rows, not the printed thresholds.)

C2 — the gain of the root split against the value you can compute on paper. With 3 Action and 2 Drama, $H = -\frac35\log_2\frac35 - \frac25\log_2\frac25 = 0.9710$ bits; the split roles >= 15 gives a pure 2-row Action leaf and a 3-row node with entropy $0.9183$, so $\mathrm{IG} = 0.9710 - \frac35 \cdot 0.9183 = 0.4200$. Assert your number matches to 1e-9.

C3 — depth and training predictions. Same depth as sklearn's tree, and the same predicted label on all five training rows.

C4 — the honest one. Print the gains of all candidate splits inside the right-hand child of the root and count how many of them are tied for the maximum. Then compare what your tree and sklearn's predict for the two test movies of part (b), and explain any disagreement.

In [ ]:
from sklearn.tree import DecisionTreeClassifier, export_text

# TODO C1: fit DecisionTreeClassifier(criterion="entropy", random_state=0),
# print export_text, and compare the row partition induced by the two roots.
# TODO C2: assert the root gain equals 0.9709505944546686 - 0.6 * 0.9182958340544896
# TODO C3: same depth, same predictions on the five training rows.
# TODO C4: tied candidate gains in the right child; predictions on the two
# test movies from both trees.
...

TODO (your reading of C4: do the two trees agree on the test movies, and what does that tell you?)

Exercise 5 — Perceptron and kNN with scikit-learn¶

A toy two-dimensional data set:

x1 = [1, 5, 1.5, 8, 1, 9]
x2 = [2, 8, 1.8, 8, 0.6, 11]
y  = [0, 1, 0, 1, 0, 1]

(a) Look at it first¶

Scatter-plot the six points, coloured by their label. How many clusters do you see?

In [ ]:
x1 = [1, 5, 1.5, 8, 1, 9]
x2 = [2, 8, 1.8, 8, 0.6, 11]
y = np.array([0, 1, 0, 1, 0, 1])
X_toy = np.column_stack([x1, x2])

# TODO: scatter plot, coloured by y, with a legend.
...

TODO (how many clusters do you see?)

(b, c, d) Perceptron, kNN, and one prediction¶

Fit both classifiers on all six points and predict the class of $x^\* = (0.58, 0.76)$:

  • Perceptron — a linear classifier trained by the perceptron rule. Set random_state=0; its shuffling is random, and without a seed you and your neighbour can fit different lines.
  • KNeighborsClassifier — use n_neighbors=3. The default is 5, which on a six-point training set means every prediction is taken by a majority of five out of six points and the "local" in "local method" is gone.

Report both classifiers in the same format: the predicted label and a confidence. Note that kNN has predict_proba (the vote shares of the neighbours) and Perceptron does not — it is a hard-margin linear rule with no probability model, so its natural confidence is the signed distance to the decision boundary, decision_function. Select on hasattr, not on a bare except: — a bare except swallows typos, shape errors and KeyboardInterrupt alike, and will one day hide a real bug from you.

In [ ]:
from sklearn.linear_model import Perceptron
from sklearn.neighbors import KNeighborsClassifier

x_star = np.array([[0.58, 0.76]])


def fit_and_report(model, name):
    # TODO: fit on (X_toy, y), predict x_star, and print
    # "name: label L, <confidence>" using predict_proba if the model has it
    # and decision_function otherwise. No bare except.
    ...


# TODO: report Perceptron(random_state=0) and
# KNeighborsClassifier(n_neighbors=3).
...

(e) Certify it¶

C1 — both classifiers agree on $x^\*$, and both reproduce all six training labels (score(X, y) == 1.0). On data this cleanly separated, a disagreement would mean an implementation or scaling mistake, not an interesting modelling difference.

C2 — the kNN vote is unanimous. assert that the three neighbours of $x^\*$ all carry label 0, so predict_proba is exactly [1.0, 0.0].

C3 — the perceptron is on the right side of its own line. Check by hand that $\mathrm{sign}(w \cdot x^\* + b)$ reproduces predict.

In [ ]:
# TODO C1: both predictions equal, both training scores == 1.0
# TODO C2: the 3 neighbours of x_star all have label 0
# TODO C3: sign(w . x_star + b) reproduces perceptron.predict
...