{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Foundations of Machine Learning - Session 04\n",
"\n",
"- *Course*: Foundations of Machine Learning\n",
"- *Session*: 04\n",
"- *Unit*: Bayes Classifier\n",
"\n",
"This notebook develops a Naive Bayes classifier in Numpy."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data\n",
"\n",
"For this notebooks' classifiction task, we will utilize text data for the first time. The code block below is pre-filled to load the Twenty Newsgroups dataset, which comprises newsgroups posts on 20 topics. One is displayed below for reference.\n",
"\n",
"To make the text data machine-readable, we transform each post into a vector of token counts. The dataset is thus transformed into a matrix of size `(n_samples, n_terms)` where `n_samples` is the number of posts and `n_terms` is the size of the vocabulary. Each row of the matrix is a feature vector, and each cell $(i,j)$ denotes how often term $j$ occurs in document $i$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_20newsgroups\n",
"from sklearn.feature_extraction.text import CountVectorizer\n",
"\n",
"data = fetch_20newsgroups(remove=[\"headers\", \"footers\", \"quotes\"])\n",
"\n",
"# CountVectorizer represents each text as vector of token counts\n",
"vectorizer = CountVectorizer(max_features=2**15)\n",
"\n",
"# Assemble D\n",
"D = list(zip(\n",
" vectorizer.fit_transform(data.data).toarray(),\n",
" data.target\n",
"))\n",
"\n",
"print(\"-\"*10, data.target_names[data.target[0]], \"-\"*10)\n",
"print(data.data[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another new concept compared to the last week is train/test splits. To make sure that the classifier generalizes well, we want to test its performance on data it has never encountered before. Therefore, we reserve some data for testing, and only use a subset for training.\n",
"\n",
"**Exercise**: split $D$ into two random subsets, a training set $D_\\text{train}$ which contains 80% of the data and a test set $D_\\text{test}$ which contains 20% of the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Naive Bayes Classification\n",
"\n",
"Recall the definition of the naive bayes classifier from lecture slide [ML:VII-84]():\n",
"$$\n",
"\\begin{aligned}\n",
"P(A_i \\mid B_1,...,B_p) &= \\frac{P(A_i) \\cdot P(B_1, ..., B_p \\mid A_i)}{P(B_1, ..., B_p)} \\\\\n",
"\t\t\t\t\t\t&= \\frac{P(A_i)\\cdot\\prod^{p}_{j=1} P(B_j \\mid A_i)}{\\sum^{k}_{i=1}P(A_i)\\cdot\\prod^{p}_{j=1} P(B_j\\mid A_i)}\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"Here, $P(A_i)$ is the prior probability of class $A_i$, and $P(B_j\\mid A_i)$ is the posterior probability of feature $B_j$ given $A_i$. To build a bayes classifier, we first have to infer both of these probabilities from the training data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Estimating Prior Probabilities\n",
"\n",
"**Exercise**: compute the prior probability for every class in the dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def priors(D):\n",
" \"\"\"\n",
" Computes the prior probabilities P(A_i) from D.\n",
" \n",
" :param D: training dataset to estimate prior probabilities from\n",
" :return: one-dimensional array of size (n_classes) where each cell denotes the prior probability P(A_i) of class A_i\n",
" \"\"\"\n",
" # TODO\n",
" return"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Estimating Posterior Probabilities\n",
"\n",
"**Exercise**: compute the posterior probabilities for every feature/class combination in the dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def posteriors(D):\n",
" \"\"\"\n",
" Computes the posterior probabilities P(B_j | A_j) for all classes A_i and all features B_j\n",
" \n",
" :param D: Dataset to estimate probabilities from\n",
" :return: two-dimensional array of size (n_classes, n_features) where cell (i, j) denotes P(B_j | A_i)\n",
" \"\"\"\n",
" # TODO\n",
" return"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Assembling the classifier\n",
"\n",
"Given both prior and posterior probabilities, we can implement the bayes classifier using the formula given previously. However, one problem might occur: if a term never occurs in a class ($P(B_j | A_i) = 0$, no matter what other features occur in a sample, the class prediction will always be 0. Therefore, we add a small value $\\alpha$ to every probability to avoid multiplying by 0.\n",
"\n",
"**Exercise**: implement a Bayes classifier following the formula from the lecture.\n",
"\n",
"*Hint*: add $\\alpha$ to the prior and posterior probabilities to increase robustness."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def predict(D, priors, posteriors, alpha=1e-6, return_probs=False):\n",
" \"\"\"\n",
" Predicts classes for test dataset D.\n",
"\n",
" :param D: test dataset to predict classes for\n",
" :param priors: prior probabilities from the train dataset\n",
" :param posteriors: posterior probabilities from the test dataset\n",
" :param alpha: alpha-value to add to the probability inputs\n",
" :param return_probs: whether to return raw probabilities (True) or just the most likely class label (False)\n",
" :return: if returning raw probabilities, returns array of size (n_samples, n_classes) where each cell denotes the class probability for that sample; if returning class labels, returns array of size (n_samples), where each cell is the most likely class of that sample\n",
" \"\"\"\n",
" # TODO\n",
" return"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Investigate the output of the classifier for $D_\\text{test}$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Rebuilding the classifier in log space\n",
"\n",
"We can observe that some probabilities are really, really small! This might become a problem due to our naive implementation: since we multiply many probabilities, the value eventually underflows, i.e. is smaller than the smallest float64-representable number. Thus, there is no discernible difference to 0 anymore.\n",
"\n",
"The solution is implement our classifier using [log probabilities](https://en.wikipedia.org/wiki/Log_probability) instead. Simply transform the probabilities to log space and replace mathematical operations in your implementation using the log-space equivalents. For convenience, `log_add` is implemented below. If you are new to log probabilities, give the linked resources a read."
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"def log_add(a, b):\n",
" # Addition in log space, see https://en.wikipedia.org/wiki/Log_probability#Addition_in_log_space for derivation of formula\n",
" return a + np.log1p(np.exp(b-a))"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise**: adapt your `predict` implementation to log-space.\n",
"\n",
"*Hint*:\n",
"- `reduce` might come in handy when constructing sums of log-probability arrays.\n",
"- do not forget to cast back the final predictions to real space using `np.exp`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from functools import reduce\n",
"\n",
"def predict_log(D, priors, posteriors, alpha=1e-6, return_probs=False):\n",
" \"\"\"\n",
" Predicts classes for test dataset D in log space.\n",
"\n",
" :param D: test dataset to predict classes for\n",
" :param priors: prior probabilities from the train dataset\n",
" :param posteriors: posterior probabilities from the test dataset\n",
" :param alpha: alpha-value to add to the probability inputs\n",
" :param return_probs: whether to return raw probabilities (True) or just the most likely class label (False)\n",
" :return: if returning raw probabilities, returns array of size (n_samples, n_classes) where each cell denotes the class probability for that sample; if returning class labels, returns array of size (n_samples), where each cell is the most likely class of that sample\n",
" \"\"\"\n",
" # TODO\n",
" return"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluation\n",
"\n",
"**Exercise**: evaluate your classifier by comparing the predicted labels to the ground-truth labels of $D_\\text{test}$.\n",
"\n",
"*Hint*: you can either use your own evaluation implementation from a previous lab, or use the `sklearn` metric implementations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.6"
}
},
"nbformat": 4,
"nbformat_minor": 1
}