handson-ml/03_classification.ipynb

2588 lines
71 KiB
Plaintext
Raw Normal View History

2016-05-22 17:40:18 +02:00
{
"cells": [
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
"**Chapter 3 Classification**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2017-08-19 17:01:55 +02:00
"_This notebook contains all the sample code and solutions to the exercises in chapter 3._"
2016-09-27 23:31:21 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<table align=\"left\">\n",
" <td>\n",
2021-05-25 21:40:58 +02:00
" <a href=\"https://colab.research.google.com/github/ageron/handson-ml2/blob/master/03_classification.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
" </td>\n",
" <td>\n",
2021-10-18 03:07:25 +02:00
" <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/ageron/handson-ml2/blob/master/03_classification.ipynb\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" /></a>\n",
" </td>\n",
"</table>"
]
},
2016-09-27 23:31:21 +02:00
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-09-27 23:31:21 +02:00
"source": [
"# Setup"
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-09-27 23:31:21 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"Let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures."
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-17 03:27:34 +02:00
"# Python ≥3.8 is required\n",
"import sys\n",
2021-10-17 03:27:34 +02:00
"assert sys.version_info >= (3, 8)\n",
2021-05-25 02:07:29 +02:00
"\n",
2021-10-29 07:03:30 +02:00
"# Scikit-Learn ≥1.0.1 is required\n",
"import sklearn\n",
2021-10-29 07:03:30 +02:00
"assert sklearn.__version__ >= \"1.0.1\""
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
"# MNIST"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.datasets import fetch_openml\n",
2021-10-29 07:03:30 +02:00
"\n",
2021-10-30 21:28:30 +02:00
"mnist = fetch_openml('mnist_784', version=1, as_frame=False)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
2016-05-22 17:40:18 +02:00
"source": [
2021-10-30 21:28:30 +02:00
"# Not in the book\n",
"mnist.keys()"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
"execution_count": 4,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-30 21:28:30 +02:00
"print(mnist.DESCR)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
"execution_count": 5,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
2021-10-30 21:28:30 +02:00
"source": [
"mnist.data"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"mnist.target"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"import numpy as np\n",
"\n",
2021-10-30 21:28:30 +02:00
"X, y = mnist.data, mnist.target\n",
2021-10-29 07:03:30 +02:00
"X.shape"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 8,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y.shape"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"28 * 28"
]
},
2016-05-22 17:40:18 +02:00
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-29 07:03:30 +02:00
"The following cell is not shown in the book. It's just here to define the default font size for the figures, and to define the `save_fig()` function which is used to save the figures in high-resolution for the book, just like we did in the previous chapter:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 10,
"metadata": {},
"outputs": [],
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"# To plot pretty figures\n",
"from pathlib import Path\n",
"import matplotlib as mpl\n",
"\n",
"mpl.rc('font', size=12)\n",
"mpl.rc('axes', labelsize=14, titlesize=14)\n",
"mpl.rc('legend', fontsize=14)\n",
"\n",
"# To save the figures in high-res for the book\n",
"IMAGES_PATH = Path() / \"images\" / \"classification\"\n",
"IMAGES_PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
"def save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n",
" path = IMAGES_PATH / f\"{fig_id}.{fig_extension}\"\n",
" if tight_layout:\n",
" plt.tight_layout()\n",
" plt.savefig(path, format=fig_extension, dpi=resolution)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 11,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"import matplotlib as mpl\n",
"import matplotlib.pyplot as plt\n",
"\n",
2021-10-29 07:03:30 +02:00
"def plot_digit(image_data):\n",
" image = image_data.reshape(28, 28)\n",
" plt.imshow(image, cmap=mpl.cm.binary, interpolation=\"nearest\")\n",
" plt.axis(\"off\")\n",
"\n",
2021-10-29 07:03:30 +02:00
"some_digit = X[0]\n",
"plot_digit(some_digit)\n",
"\n",
2021-10-29 07:03:30 +02:00
"save_fig(\"some_digit_plot\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 12,
2017-07-07 21:56:30 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y[0]"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 13,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"plt.figure(figsize=(9, 9))\n",
"for idx, image_data in enumerate(X[:100]):\n",
" plt.subplot(10, 10, idx + 1)\n",
" plot_digit(image_data)\n",
"plt.subplots_adjust(wspace=0, hspace=0)\n",
"save_fig(\"more_digits_plot\", tight_layout=False)\n",
"plt.show()"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 14,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-02 13:14:44 +02:00
"# Training a Binary Classifier"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 15,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-30 21:28:30 +02:00
"y_train_5 = (y_train == '5')\n",
"y_test_5 = (y_test == '5')"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 16,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.linear_model import SGDClassifier\n",
"\n",
2021-10-29 07:03:30 +02:00
"sgd_clf = SGDClassifier(random_state=42)\n",
2016-05-22 17:40:18 +02:00
"sgd_clf.fit(X_train, y_train_5)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 17,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"sgd_clf.predict([some_digit])"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 18,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2016-11-05 18:13:54 +01:00
"from sklearn.model_selection import cross_val_score\n",
2021-10-29 07:03:30 +02:00
"\n",
2016-05-22 17:40:18 +02:00
"cross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring=\"accuracy\")"
]
},
2021-10-02 13:14:44 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Performance Measures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Measuring Accuracy Using Cross-Validation"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 19,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2016-11-05 18:13:54 +01:00
"from sklearn.model_selection import StratifiedKFold\n",
2016-05-22 17:40:18 +02:00
"\n",
2020-11-21 00:22:42 +01:00
"skfolds = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\n",
2016-05-22 17:40:18 +02:00
"\n",
2016-11-05 18:13:54 +01:00
"for train_index, test_index in skfolds.split(X_train, y_train_5):\n",
2016-05-22 17:40:18 +02:00
" X_train_folds = X_train[train_index]\n",
" y_train_folds = y_train_5[train_index]\n",
2016-05-22 17:40:18 +02:00
" X_test_fold = X_train[test_index]\n",
" y_test_fold = y_train_5[test_index]\n",
2016-11-05 18:13:54 +01:00
"\n",
2021-10-29 07:03:30 +02:00
" sgd_clf_cv = SGDClassifier(random_state=42)\n",
" sgd_clf_cv.fit(X_train_folds, y_train_folds)\n",
" y_pred = sgd_clf_cv.predict(X_test_fold)\n",
2016-05-22 17:40:18 +02:00
" n_correct = sum(y_pred == y_test_fold)\n",
" print(n_correct / len(y_pred))"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 20,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"from sklearn.dummy import DummyClassifier\n",
"\n",
"dummy_clf = DummyClassifier()\n",
"dummy_clf.fit(X_train, y_train_5)\n",
"np.any(dummy_clf.predict(X_train))"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 21,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"cross_val_score(dummy_clf, X_train, y_train_5, cv=3, scoring=\"accuracy\")"
2020-11-21 00:22:42 +01:00
]
},
2021-10-02 13:14:44 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Confusion Matrix"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 22,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2016-11-05 18:13:54 +01:00
"from sklearn.model_selection import cross_val_predict\n",
2016-05-22 17:40:18 +02:00
"\n",
"y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 23,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import confusion_matrix\n",
"\n",
"confusion_matrix(y_train_5, y_train_pred)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"y_train_perfect_predictions = y_train_5 # pretend we reached perfection\n",
"confusion_matrix(y_train_5, y_train_perfect_predictions)"
]
},
2021-10-02 13:14:44 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Precision and Recall"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 25,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import precision_score, recall_score\n",
"\n",
"precision_score(y_train_5, y_train_pred)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 26,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2020-11-21 00:22:42 +01:00
"cm = confusion_matrix(y_train_5, y_train_pred)\n",
"cm[1, 1] / (cm[0, 1] + cm[1, 1])"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 27,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"recall_score(y_train_5, y_train_pred)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 28,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2020-11-21 00:22:42 +01:00
"cm[1, 1] / (cm[1, 0] + cm[1, 1])"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 29,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import f1_score\n",
"\n",
2016-05-22 17:40:18 +02:00
"f1_score(y_train_5, y_train_pred)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 30,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2020-11-21 00:22:42 +01:00
"cm[1, 1] / (cm[1, 1] + (cm[1, 0] + cm[0, 1]) / 2)"
2016-05-22 17:40:18 +02:00
]
},
2021-10-02 13:14:44 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Precision/Recall Trade-off"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 31,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"y_scores = sgd_clf.decision_function([some_digit])\n",
"y_scores"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 32,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"threshold = 0\n",
"y_some_digit_pred = (y_scores > threshold)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 33,
2017-07-07 21:56:30 +02:00
"metadata": {},
"outputs": [],
"source": [
2016-05-22 17:40:18 +02:00
"y_some_digit_pred"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 34,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"threshold = 8000\n",
2016-05-22 17:40:18 +02:00
"y_some_digit_pred = (y_scores > threshold)\n",
"y_some_digit_pred"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 35,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3,\n",
" method=\"decision_function\")"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 36,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import precision_recall_curve\n",
"\n",
"precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 37,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"recall_90_precision = recalls[np.argmax(precisions >= 0.90)]\n",
"threshold_90_precision = thresholds[np.argmax(precisions >= 0.90)]\n",
"\n",
2021-10-29 07:03:30 +02:00
"plt.figure(figsize=(8, 4)) # not in the book\n",
"plt.plot(thresholds, precisions[:-1], \"b--\", label=\"Precision\", linewidth=2)\n",
"plt.plot(thresholds, recalls[:-1], \"g-\", label=\"Recall\", linewidth=2)\n",
"plt.vlines(threshold_90_precision, 0, 1.0, \"k\", \"dotted\", label=\"threshold\")\n",
"\n",
"# not in the book (just beautifies the figure)\n",
"plt.plot(threshold_90_precision, recall_90_precision, \"go\")\n",
"plt.plot(threshold_90_precision, 0.90, \"bo\")\n",
"plt.axis([-50000, 50000, 0, 1])\n",
"plt.grid(True)\n",
"plt.xlabel(\"Threshold\")\n",
"plt.legend(loc=\"center right\")\n",
"save_fig(\"precision_recall_vs_threshold_plot\")\n",
"\n",
2016-05-22 17:40:18 +02:00
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 38,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"(y_train_pred == (y_scores > 0)).all()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 39,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"plt.figure(figsize=(8, 6)) # not in the book\n",
"\n",
2021-10-29 07:03:30 +02:00
"plt.plot(recalls, precisions, linewidth=2)\n",
"plt.plot([recall_90_precision, recall_90_precision], [0., 0.9], \"k:\")\n",
"plt.plot([0.0, recall_90_precision], [0.9, 0.9], \"k:\")\n",
"plt.plot([recall_90_precision], [0.9], \"ko\")\n",
"\n",
"# not in the book (just beautifies the figure)\n",
"plt.xlabel(\"Recall\")\n",
"plt.ylabel(\"Precision\")\n",
"plt.axis([0, 1, 0, 1])\n",
"plt.grid(True)\n",
"save_fig(\"precision_vs_recall_plot\")\n",
2021-10-29 07:03:30 +02:00
"\n",
"plt.show()"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 40,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"threshold_90_precision = thresholds[np.argmax(precisions >= 0.90)]"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 41,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"threshold_90_precision"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 42,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"y_train_pred_90 = (y_scores >= threshold_90_precision)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"precision_score(y_train_5, y_train_pred_90)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"recall_score(y_train_5, y_train_pred_90)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-02 13:14:44 +02:00
"## The ROC Curve"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 45,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import roc_curve\n",
"\n",
"fpr, tpr, thresholds = roc_curve(y_train_5, y_scores)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 46,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"def plot_roc_curve(fpr, tpr, label=None):\n",
2021-10-29 07:03:30 +02:00
" plt.plot(fpr, tpr, linewidth=2, label=label) # ROC curve\n",
" plt.plot([0, 1], [0, 1], 'k--') # dashed diagonal\n",
"\n",
" # not in the book (just beautifies the figure)\n",
" plt.axis([0, 1, 0, 1])\n",
" plt.xlabel('False Positive Rate (Fall-Out)')\n",
" plt.ylabel('True Positive Rate (Recall)')\n",
" plt.grid(True)\n",
"\n",
"\n",
"plt.figure(figsize=(8, 6)) # Not in the book\n",
2016-05-22 17:40:18 +02:00
"plot_roc_curve(fpr, tpr)\n",
2021-10-29 07:03:30 +02:00
"\n",
"# not in the book (just beautifies the figure)\n",
"fpr_90 = fpr[np.argmax(tpr >= recall_90_precision)]\n",
"plt.plot([fpr_90, fpr_90], [0., recall_90_precision], \"r:\")\n",
"plt.plot([0.0, fpr_90], [recall_90_precision, recall_90_precision], \"r:\")\n",
"plt.plot([fpr_90], [recall_90_precision], \"ro\")\n",
"save_fig(\"roc_curve_plot\")\n",
"\n",
2016-05-22 17:40:18 +02:00
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 47,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.metrics import roc_auc_score\n",
"\n",
"roc_auc_score(y_train_5, y_scores)"
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 48,
"metadata": {},
2021-10-29 07:03:30 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"from sklearn.ensemble import RandomForestClassifier\n",
"\n",
"forest_clf = RandomForestClassifier(random_state=42)\n",
"y_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3,\n",
" method=\"predict_proba\")"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 49,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y_probas_forest.shape"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y_scores_forest = y_probas_forest[:, 1] # 2nd column = proba of positive class\n",
"fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5,y_scores_forest)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 51,
2017-07-07 21:56:30 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"# not in the book\n",
2020-11-21 00:22:42 +01:00
"recall_for_forest = tpr_forest[np.argmax(fpr_forest >= fpr_90)]\n",
"\n",
2016-05-22 17:40:18 +02:00
"plt.figure(figsize=(8, 6))\n",
"plt.plot(fpr, tpr, \"b:\", linewidth=2, label=\"SGD\")\n",
"plot_roc_curve(fpr_forest, tpr_forest, \"Random Forest\")\n",
2020-11-21 00:22:42 +01:00
"plt.plot([fpr_90, fpr_90], [0., recall_90_precision], \"r:\")\n",
"plt.plot([0.0, fpr_90], [recall_90_precision, recall_90_precision], \"r:\")\n",
"plt.plot([fpr_90], [recall_90_precision], \"ro\")\n",
"plt.plot([fpr_90, fpr_90], [0., recall_for_forest], \"r:\")\n",
"plt.plot([fpr_90], [recall_for_forest], \"ro\")\n",
"plt.grid(True)\n",
2021-10-29 07:03:30 +02:00
"plt.legend(loc=\"lower right\")\n",
2016-05-22 17:40:18 +02:00
"save_fig(\"roc_curve_comparison_plot\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 52,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"roc_auc_score(y_train_5, y_scores_forest)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 53,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"y_train_pred_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3)\n",
"precision_score(y_train_5, y_train_pred_forest)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 54,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"recall_score(y_train_5, y_train_pred_forest)"
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-02 13:14:44 +02:00
"# Multiclass Classification"
2016-05-22 17:40:18 +02:00
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-30 21:28:30 +02:00
"SVMs do not scale well to large datasets, so let's only train on the first 2,000 instances, or else this section will take a very long time to run:"
2021-10-29 07:03:30 +02:00
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 55,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.svm import SVC\n",
"\n",
"svm_clf = SVC(gamma=\"auto\", random_state=42)\n",
2021-10-30 21:28:30 +02:00
"svm_clf.fit(X_train[:2000], y_train[:2000]) # y_train, not y_train_5\n",
"svm_clf.predict([some_digit])"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 56,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"some_digit_scores = svm_clf.decision_function([some_digit])\n",
2021-10-29 07:03:30 +02:00
"np.round(some_digit_scores, 2)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 57,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"# Not in the book\n",
"svm_clf.decision_function_shape = \"ovo\"\n",
"some_digit_scores_ovo = svm_clf.decision_function([some_digit])\n",
"np.round(some_digit_scores_ovo, 2)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 58,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-30 21:28:30 +02:00
"class_id = np.argmax(some_digit_scores)\n",
"class_id"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 59,
2017-07-07 21:56:30 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"svm_clf.classes_"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 60,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-30 21:28:30 +02:00
"svm_clf.classes_[class_id]"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 61,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"from sklearn.multiclass import OneVsRestClassifier\n",
"\n",
"ovr_clf = OneVsRestClassifier(SVC(gamma=\"auto\", random_state=42))\n",
"ovr_clf.fit(X_train[:2000], y_train[:2000])\n",
"ovr_clf.predict([some_digit])"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 62,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"len(ovr_clf.estimators_)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 63,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"sgd_clf = SGDClassifier(random_state=42)\n",
"sgd_clf.fit(X_train[:2000], y_train[:2000])\n",
"sgd_clf.predict([some_digit])"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 64,
"metadata": {},
2021-10-29 07:03:30 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"np.round(sgd_clf.decision_function([some_digit]))"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 65,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"cross_val_score(sgd_clf, X_train[:2000], y_train[:2000],\n",
" cv=3, scoring=\"accuracy\")"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 66,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"from sklearn.preprocessing import StandardScaler\n",
2021-10-29 07:03:30 +02:00
"\n",
2016-05-22 17:40:18 +02:00
"scaler = StandardScaler()\n",
"X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))\n",
2021-10-29 07:03:30 +02:00
"cross_val_score(sgd_clf, X_train_scaled[:2000], y_train[:2000],\n",
" cv=3, scoring=\"accuracy\")"
2016-05-22 17:40:18 +02:00
]
},
2021-01-28 05:12:29 +01:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-02 13:14:44 +02:00
"# Error Analysis"
2021-01-28 05:12:29 +01:00
]
},
2021-10-30 21:28:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Warning:** the following cell will take a few minutes to run:"
]
},
2016-05-22 17:40:18 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 67,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y_train_pred = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 68,
2017-07-07 21:56:30 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"from sklearn.metrics import ConfusionMatrixDisplay\n",
"\n",
"ConfusionMatrixDisplay.from_predictions(y_train, y_train_pred)\n",
"save_fig(\"confusion_matrix_plot\")\n",
2016-05-22 17:40:18 +02:00
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 69,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"error_idx = y_train_pred != y_train\n",
"y_train_pred_error = y_train_pred[error_idx]\n",
"y_train_error = y_train[error_idx]\n",
"ConfusionMatrixDisplay.from_predictions(y_train_error, y_train_pred_error,\n",
" normalize=\"pred\", values_format=\".0%\")\n",
2016-05-22 17:40:18 +02:00
"save_fig(\"confusion_matrix_errors_plot\", tight_layout=False)\n",
"plt.show()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 70,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-30 21:28:30 +02:00
"cl_a, cl_b = '3', '5'\n",
2016-05-22 17:40:18 +02:00
"X_aa = X_train[(y_train == cl_a) & (y_train_pred == cl_a)]\n",
"X_ab = X_train[(y_train == cl_a) & (y_train_pred == cl_b)]\n",
"X_ba = X_train[(y_train == cl_b) & (y_train_pred == cl_a)]\n",
2021-10-29 07:03:30 +02:00
"X_bb = X_train[(y_train == cl_b) & (y_train_pred == cl_b)]"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 71,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"# not in the book\n",
"size = 5\n",
"pad = 0.2\n",
"plt.figure(figsize=(size, size))\n",
"for images, (label_col, label_row) in [(X_ba, (0, 0)), (X_bb, (1, 0)),\n",
" (X_aa, (0, 1)), (X_ab, (1, 1))]:\n",
" for idx, image_data in enumerate(images[:size*size]):\n",
" x = idx % size + label_col * (size + pad)\n",
" y = idx // size + label_row * (size + pad)\n",
" plt.imshow(image_data.reshape(28, 28), cmap=\"binary\",\n",
" extent=(x, x + 1, y, y + 1))\n",
"plt.xticks([size / 2, size + pad + size / 2], [str(cl_a), str(cl_b)])\n",
"plt.yticks([size / 2, size + pad + size / 2], [str(cl_b), str(cl_a)])\n",
"plt.plot([size + pad / 2, size + pad / 2], [0, 2 * size + pad], \"k:\")\n",
"plt.plot([0, 2 * size + pad], [size + pad / 2, size + pad / 2], \"k:\")\n",
"plt.axis([0, 2 * size + pad, 0, 2 * size + pad])\n",
"plt.xlabel(\"Predicted label\")\n",
"plt.ylabel(\"True label\")\n",
"save_fig(\"error_analysis_digits_plot\")\n",
2016-05-22 17:40:18 +02:00
"plt.show()"
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"Note: there are several other ways you could code a plot like this one, but it's a bit hard to get the axis labels right:\n",
"* using [nested GridSpecs](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/gridspec_nested.html)\n",
"* merging all the digits in each block into a single image (then using 2×2 subplots). For example:\n",
" ```python\n",
" X_aa[:25].reshape(5, 5, 28, 28).transpose(0, 2, 1, 3).reshape(5 * 28, 5 * 28)\n",
" ```\n",
"* using [subfigures](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subfigures.html) (since Matplotlib 3.4)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"# Multilabel Classification"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 72,
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"from sklearn.neighbors import KNeighborsClassifier\n",
"\n",
2021-10-30 21:28:30 +02:00
"y_train_large = (y_train >= '7')\n",
"y_train_odd = (y_train.astype(np.uint8) % 2 == 1)\n",
2021-10-29 07:03:30 +02:00
"y_multilabel = np.c_[y_train_large, y_train_odd]\n",
"\n",
"knn_clf = KNeighborsClassifier()\n",
"knn_clf.fit(X_train, y_multilabel)"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 73,
2021-10-29 07:03:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"knn_clf.predict([some_digit])"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"**Warning**: the following cell may take a few minutes:"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 74,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3)\n",
"f1_score(y_multilabel, y_train_knn_pred, average=\"macro\")"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"# Multioutput Classification"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 75,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
"np.random.seed(42)\n",
2021-10-29 07:03:30 +02:00
"noise = np.random.randint(0, 100, (len(X_train), 784))\n",
"X_train_mod = X_train + noise\n",
"noise = np.random.randint(0, 100, (len(X_test), 784))\n",
"X_test_mod = X_test + noise\n",
"y_train_mod = X_train\n",
"y_test_mod = X_test"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 76,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"some_index = 0\n",
"plt.subplot(121); plot_digit(X_test_mod[some_index])\n",
"plt.subplot(122); plot_digit(y_test_mod[some_index])\n",
"save_fig(\"noisy_digit_example_plot\")\n",
"plt.show()"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 77,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"knn_clf.fit(X_train_mod, y_train_mod)\n",
"clean_digit = knn_clf.predict([X_test_mod[some_index]])\n",
"plot_digit(clean_digit)\n",
"save_fig(\"cleaned_digit_example_plot\")\n",
"plt.show()"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"# Exercise solutions"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"## 1. An MNIST Classifier With Over 97% Accuracy"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"Exercise: _Try to build a classifier for the MNIST dataset that achieves over 97% accuracy on the test set. Hint: the `KNeighborsClassifier` works quite well for this task; you just need to find good hyperparameter values (try a grid search on the `weights` and `n_neighbors` hyperparameters)._"
2016-05-22 17:40:18 +02:00
]
},
{
2021-10-29 07:03:30 +02:00
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"Let's start with a simple K-Nearest Neighbors classifier and measure its performance on the test set. This will be our baseline:"
2016-05-22 17:40:18 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 78,
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-05-22 17:40:18 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"knn_clf = KNeighborsClassifier()\n",
"knn_clf.fit(X_train, y_train)\n",
"baseline_accuracy = knn_clf.score(X_test, y_test)\n",
"baseline_accuracy"
2016-09-27 23:31:21 +02:00
]
},
{
"cell_type": "markdown",
2017-07-07 21:56:30 +02:00
"metadata": {},
2016-09-27 23:31:21 +02:00
"source": [
2021-10-29 07:03:30 +02:00
"Great! A regular KNN classifier with the default hyperparameters is already very close to our goal."
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-29 07:03:30 +02:00
"Let's see if we tuning the hyperparameters can help. To speed up the search, let's train only on the first 10,000 images:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 79,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import GridSearchCV\n",
"\n",
2021-10-29 07:03:30 +02:00
"param_grid = [{'weights': [\"uniform\", \"distance\"], 'n_neighbors': [3, 4, 5, 6]}]\n",
2017-10-04 10:57:40 +02:00
"\n",
"knn_clf = KNeighborsClassifier()\n",
2021-10-29 07:03:30 +02:00
"grid_search = GridSearchCV(knn_clf, param_grid, cv=5)\n",
"grid_search.fit(X_train[:10_000], y_train[:10_000])"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 80,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"grid_search.best_params_"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 81,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"grid_search.best_score_"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The score dropped, but that was expected since we only trained on 10,000 images. So let's take the best model and train it again on the full training set:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 82,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"grid_search.best_estimator_.fit(X_train, y_train)\n",
"tuned_accuracy = grid_search.score(X_test, y_test)\n",
"tuned_accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We reached our goal of 97% accuracy! 🥳"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Data Augmentation"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exercise: _Write a function that can shift an MNIST image in any direction (left, right, up, or down) by one pixel. You can use the `shift()` function from the `scipy.ndimage.interpolation` module. For example, `shift(image, [2, 1], cval=0)` shifts the image two pixels down and one pixel to the right. Then, for each image in the training set, create four shifted copies (one per direction) and add them to the training set. Finally, train your best model on this expanded training set and measure its accuracy on the test set. You should observe that your model performs even better now! This technique of artificially growing the training set is called _data augmentation_ or _training set expansion_._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try augmenting the MNIST dataset by adding slightly shifted versions of each image."
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 83,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"from scipy.ndimage.interpolation import shift"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 84,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"def shift_image(image, dx, dy):\n",
" image = image.reshape((28, 28))\n",
" shifted_image = shift(image, [dy, dx], cval=0, mode=\"constant\")\n",
" return shifted_image.reshape([-1])"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see if it works:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 85,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"image = X_train[1000] # some random digit to demo\n",
2017-10-04 10:57:40 +02:00
"shifted_image_down = shift_image(image, 0, 5)\n",
"shifted_image_left = shift_image(image, -5, 0)\n",
"\n",
"plt.figure(figsize=(12,3))\n",
"plt.subplot(131)\n",
2021-10-29 07:03:30 +02:00
"plt.title(\"Original\")\n",
"plt.imshow(image.reshape(28, 28),\n",
" interpolation=\"nearest\", cmap=\"Greys\")\n",
2017-10-04 10:57:40 +02:00
"plt.subplot(132)\n",
2021-10-29 07:03:30 +02:00
"plt.title(\"Shifted down\")\n",
"plt.imshow(shifted_image_down.reshape(28, 28),\n",
" interpolation=\"nearest\", cmap=\"Greys\")\n",
2017-10-04 10:57:40 +02:00
"plt.subplot(133)\n",
2021-10-29 07:03:30 +02:00
"plt.title(\"Shifted left\")\n",
"plt.imshow(shifted_image_left.reshape(28, 28),\n",
" interpolation=\"nearest\", cmap=\"Greys\")\n",
2017-10-04 10:57:40 +02:00
"plt.show()"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Looks good! Now let's create an augmented training set by shifting every image left, right, up and down by one pixel:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 86,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"X_train_augmented = [image for image in X_train]\n",
"y_train_augmented = [label for label in y_train]\n",
"\n",
2021-10-29 07:03:30 +02:00
"for dx, dy in ((-1, 0), (1, 0), (0, 1), (0, -1)):\n",
2017-10-04 10:57:40 +02:00
" for image, label in zip(X_train, y_train):\n",
" X_train_augmented.append(shift_image(image, dx, dy))\n",
" y_train_augmented.append(label)\n",
"\n",
"X_train_augmented = np.array(X_train_augmented)\n",
"y_train_augmented = np.array(y_train_augmented)"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's shuffle the augmented training set, or else all shifted images will be grouped together:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 87,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"shuffle_idx = np.random.permutation(len(X_train_augmented))\n",
"X_train_augmented = X_train_augmented[shuffle_idx]\n",
"y_train_augmented = y_train_augmented[shuffle_idx]"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's train the model using the best hyperparameters we found in the previous exercise:"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 88,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"knn_clf = KNeighborsClassifier(**grid_search.best_params_)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 89,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"knn_clf.fit(X_train_augmented, y_train_augmented)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-29 07:03:30 +02:00
"**Warning**: the following cell may take a few minutes to run."
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 90,
2021-10-29 07:03:30 +02:00
"metadata": {},
"outputs": [],
"source": [
"augmented_accuracy = knn_clf.score(X_test, y_test)"
]
},
{
"cell_type": "markdown",
2017-10-04 10:57:40 +02:00
"metadata": {},
2021-10-29 07:03:30 +02:00
"source": [
"By simply augmenting the data, we got a 0.5% accuracy boost. Perhaps this does not sound so impressive, but this actually means that the error rate dropped significantly:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 91,
2021-10-29 07:03:30 +02:00
"metadata": {
"tags": []
},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
2021-10-29 07:03:30 +02:00
"error_rate_change = (1 - augmented_accuracy) / (1 - tuned_accuracy) - 1\n",
"print(f\"error_rate_change = {error_rate_change:.0%}\")"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-29 07:03:30 +02:00
"The error rate dropped quite a bit thanks to data augmentation."
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Tackle the Titanic dataset"
]
},
2021-10-29 07:03:30 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exercise: _Tackle the Titanic dataset. A great place to start is on [Kaggle](https://www.kaggle.com/c/titanic)._"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The goal is to predict whether or not a passenger survived based on attributes such as their age, sex, passenger class, where they embarked and so on."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's fetch the data and load it:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 92,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"import pandas as pd\n",
"import urllib.request\n",
2017-10-04 10:57:40 +02:00
"\n",
"def load_titanic_data():\n",
" titanic_path = Path() / \"datasets\" / \"titanic\"\n",
" titanic_path.mkdir(parents=True, exist_ok=True)\n",
" filenames = (\"train.csv\", \"test.csv\")\n",
" for filename in filenames:\n",
" filepath = titanic_path / filename\n",
" if filepath.is_file():\n",
" continue\n",
" root = \"https://raw.githubusercontent.com/ageron/handson-ml2/master/\"\n",
" url = root + \"/datasets/titanic/\" + filename\n",
" print(\"Downloading\", filename)\n",
" urllib.request.urlretrieve(url, filepath)\n",
" return [pd.read_csv(titanic_path / filename) for filename in filenames]"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 93,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"train_data, test_data = load_titanic_data()"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The data is already split into a training set and a test set. However, the test data does *not* contain the labels: your goal is to train the best model you can using the training data, then make your predictions on the test data and upload them to Kaggle to see your final score."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a peek at the top few rows of the training set:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 94,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The attributes have the following meaning:\n",
"* **PassengerId**: a unique identifier for each passenger\n",
2017-10-04 10:57:40 +02:00
"* **Survived**: that's the target, 0 means the passenger did not survive, while 1 means he/she survived.\n",
"* **Pclass**: passenger class.\n",
"* **Name**, **Sex**, **Age**: self-explanatory\n",
"* **SibSp**: how many siblings & spouses of the passenger aboard the Titanic.\n",
"* **Parch**: how many children & parents of the passenger aboard the Titanic.\n",
"* **Ticket**: ticket id\n",
"* **Fare**: price paid (in pounds)\n",
"* **Cabin**: passenger's cabin number\n",
"* **Embarked**: where the passenger embarked the Titanic"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's explicitly set the `PassengerId` column as the index column:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 95,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data = train_data.set_index(\"PassengerId\")\n",
"test_data = test_data.set_index(\"PassengerId\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's get more info to see how much data is missing:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 96,
"metadata": {},
"outputs": [],
2017-10-04 10:57:40 +02:00
"source": [
"train_data.info()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 97,
"metadata": {},
"outputs": [],
"source": [
"train_data[train_data[\"Sex\"]==\"female\"][\"Age\"].median()"
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, the **Age**, **Cabin** and **Embarked** attributes are sometimes null (less than 891 non-null), especially the **Cabin** (77% are null). We will ignore the **Cabin** for now and focus on the rest. The **Age** attribute has about 19% null values, so we will need to decide what to do with them. Replacing null values with the median age seems reasonable. We could be a bit smarter by predicting the age based on the other columns (for example, the median age is 37 in 1st class, 29 in 2nd class and 24 in 3rd class), but we'll keep things simple and just use the overall median age."
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **Name** and **Ticket** attributes may have some value, but they will be a bit tricky to convert into useful numbers that a model can consume. So for now, we will ignore them."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a look at the numerical attributes:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 98,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Yikes, only 38% **Survived**! 😭 That's close enough to 40%, so accuracy will be a reasonable metric to evaluate our model.\n",
2017-10-04 10:57:40 +02:00
"* The mean **Fare** was £32.20, which does not seem so expensive (but it was probably a lot of money back then).\n",
"* The mean **Age** was less than 30 years old."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's check that the target is indeed 0 or 1:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 99,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"Survived\"].value_counts()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's take a quick look at all the categorical attributes:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 100,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"Pclass\"].value_counts()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 101,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"Sex\"].value_counts()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 102,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"Embarked\"].value_counts()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Embarked attribute tells us where the passenger embarked: C=Cherbourg, Q=Queenstown, S=Southampton."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's build our preprocessing pipelines, starting with the pipeline for numerical attributes:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 103,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"from sklearn.pipeline import Pipeline\n",
"from sklearn.impute import SimpleImputer\n",
2017-10-04 10:57:40 +02:00
"\n",
"num_pipeline = Pipeline([\n",
" (\"imputer\", SimpleImputer(strategy=\"median\")),\n",
" (\"scaler\", StandardScaler())\n",
2017-10-04 10:57:40 +02:00
" ])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can build the pipeline for the categorical attributes:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 104,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 105,
"metadata": {},
"outputs": [],
2017-10-04 10:57:40 +02:00
"source": [
"cat_pipeline = Pipeline([\n",
" (\"ordinal_encoder\", OrdinalEncoder()), \n",
" (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n",
" (\"cat_encoder\", OneHotEncoder(sparse=False)),\n",
2017-10-04 10:57:40 +02:00
" ])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, let's join the numerical and categorical pipelines:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 106,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"from sklearn.compose import ColumnTransformer\n",
"\n",
"num_attribs = [\"Age\", \"SibSp\", \"Parch\", \"Fare\"]\n",
"cat_attribs = [\"Pclass\", \"Sex\", \"Embarked\"]\n",
"\n",
"preprocess_pipeline = ColumnTransformer([\n",
" (\"num\", num_pipeline, num_attribs),\n",
" (\"cat\", cat_pipeline, cat_attribs),\n",
2017-10-04 10:57:40 +02:00
" ])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Cool! Now we have a nice preprocessing pipeline that takes the raw data and outputs numerical input features that we can feed to any Machine Learning model we want."
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 107,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"X_train = preprocess_pipeline.fit_transform(train_data)\n",
"X_train"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's not forget to get the labels:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 108,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"y_train = train_data[\"Survived\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are now ready to train a classifier. Let's start with a `RandomForestClassifier`:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 109,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"forest_clf = RandomForestClassifier(n_estimators=100, random_state=42)\n",
"forest_clf.fit(X_train, y_train)"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great, our model is trained, let's use it to make predictions on the test set:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 110,
"metadata": {},
2017-10-04 10:57:40 +02:00
"outputs": [],
"source": [
"X_test = preprocess_pipeline.transform(test_data)\n",
"y_pred = forest_clf.predict(X_test)"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And now we could just build a CSV file with these predictions (respecting the format excepted by Kaggle), then upload it and hope for the best. But wait! We can do better than hope. Why don't we use cross-validation to have an idea of how good our model is?"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 111,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"forest_scores = cross_val_score(forest_clf, X_train, y_train, cv=10)\n",
"forest_scores.mean()"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, not too bad! Looking at the [leaderboard](https://www.kaggle.com/c/titanic/leaderboard) for the Titanic competition on Kaggle, you can see that our score is in the top 2%, woohoo! Some Kagglers reached 100% accuracy, but since you can easily find the [list of victims](https://www.encyclopedia-titanica.org/titanic-victims/) of the Titanic, it seems likely that there was little Machine Learning involved in their performance! 😆"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try an `SVC`:"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 112,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"from sklearn.svm import SVC\n",
2017-10-04 10:57:40 +02:00
"\n",
"svm_clf = SVC(gamma=\"auto\")\n",
"svm_scores = cross_val_score(svm_clf, X_train, y_train, cv=10)\n",
"svm_scores.mean()"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great! This model looks better."
2017-10-04 10:57:40 +02:00
]
},
2018-05-26 15:01:33 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But instead of just looking at the mean accuracy across the 10 cross-validation folds, let's plot all 10 scores for each model, along with a box plot highlighting the lower and upper quartiles, and \"whiskers\" showing the extent of the scores (thanks to Nevin Yilmaz for suggesting this visualization). Note that the `boxplot()` function detects outliers (called \"fliers\") and does not include them within the whiskers. Specifically, if the lower quartile is $Q_1$ and the upper quartile is $Q_3$, then the interquartile range $IQR = Q_3 - Q_1$ (this is the box's height), and any score lower than $Q_1 - 1.5 \\times IQR$ is a flier, and so is any score greater than $Q3 + 1.5 \\times IQR$."
2018-05-26 15:01:33 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 113,
2018-05-26 15:01:33 +02:00
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(8, 4))\n",
"plt.plot([1]*10, svm_scores, \".\")\n",
"plt.plot([2]*10, forest_scores, \".\")\n",
"plt.boxplot([svm_scores, forest_scores], labels=(\"SVM\",\"Random Forest\"))\n",
2021-10-29 07:03:30 +02:00
"plt.ylabel(\"Accuracy\")\n",
2018-05-26 15:01:33 +02:00
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The random forest classifier got a very high score on one of the 10 folds, but overall it had a lower mean score, as well as a bigger spread, so it looks like the SVM classifier is more likely to generalize well."
]
},
2017-10-04 10:57:40 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To improve this result further, you could:\n",
"* Compare many more models and tune hyperparameters using cross validation and grid search,\n",
"* Do more feature engineering, for example:\n",
" * Try to convert numerical attributes to categorical attributes: for example, different age groups had very different survival rates (see below), so it may help to create an age bucket category and use it instead of the age. Similarly, it may be useful to have a special category for people traveling alone since only 30% of them survived (see below).\n",
" * Replace **SibSp** and **Parch** with their sum.\n",
" * Try to identify parts of names that correlate well with the **Survived** attribute.\n",
" * Use the **Cabin** column, for example take its first letter and treat it as a categorical attribute."
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 114,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"AgeBucket\"] = train_data[\"Age\"] // 15 * 15\n",
"train_data[[\"AgeBucket\", \"Survived\"]].groupby(['AgeBucket']).mean()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 115,
2017-10-04 10:57:40 +02:00
"metadata": {},
"outputs": [],
"source": [
"train_data[\"RelativesOnboard\"] = train_data[\"SibSp\"] + train_data[\"Parch\"]\n",
"train_data[[\"RelativesOnboard\", \"Survived\"]].groupby(\n",
" ['RelativesOnboard']).mean()"
2017-10-04 10:57:40 +02:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Spam classifier"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2021-10-29 07:03:30 +02:00
"Exercise: _Build a spam classifier (a more challenging exercise):_\n",
"\n",
"* _Download examples of spam and ham from [Apache SpamAssassin's public datasets](https://homl.info/spamassassin)._\n",
"* _Unzip the datasets and familiarize yourself with the data format._\n",
"* _Split the datasets into a training set and a test set._\n",
"* _Write a data preparation pipeline to convert each email into a feature vector. Your preparation pipeline should transform an email into a (sparse) vector that indicates the presence or absence of each possible word. For example, if all emails only ever contain four words, \"Hello,\" \"how,\" \"are,\" \"you,\" then the email \"Hello you Hello Hello you\" would be converted into a vector [1, 0, 0, 1] (meaning [“Hello\" is present, \"how\" is absent, \"are\" is absent, \"you\" is present]), or [3, 0, 0, 2] if you prefer to count the number of occurrences of each word._\n",
"\n",
"_You may want to add hyperparameters to your preparation pipeline to control whether or not to strip off email headers, convert each email to lowercase, remove punctuation, replace all URLs with \"URL,\" replace all numbers with \"NUMBER,\" or even perform _stemming_ (i.e., trim off word endings; there are Python libraries available to do this)._\n",
"\n",
"_Finally, try out several classifiers and see if you can build a great spam classifier, with both high recall and high precision._"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 116,
"metadata": {},
"outputs": [],
"source": [
"import tarfile\n",
"\n",
"def fetch_spam_data():\n",
" root = \"http://spamassassin.apache.org/old/publiccorpus/\"\n",
" ham_url = root + \"20030228_easy_ham.tar.bz2\"\n",
" spam_url = root + \"20030228_spam.tar.bz2\"\n",
"\n",
" spam_path = Path() / \"datasets\" / \"spam\"\n",
" spam_path.mkdir(parents=True, exist_ok=True)\n",
" for dir_name, tar_name, url in ((\"easy_ham\", \"ham\", ham_url),\n",
" (\"spam\", \"spam\", spam_url)):\n",
" if not (spam_path / dir_name).is_dir():\n",
" path = (spam_path / tar_name).with_suffix(\".tar.bz2\")\n",
" print(\"Downloading\", path)\n",
" urllib.request.urlretrieve(url, path)\n",
" tar_bz2_file = tarfile.open(path)\n",
" tar_bz2_file.extractall(path=spam_path)\n",
" tar_bz2_file.close()\n",
" return [spam_path / dir_name for dir_name in (\"easy_ham\", \"spam\")]"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 117,
"metadata": {},
"outputs": [],
"source": [
"ham_dir, spam_dir = fetch_spam_data()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, let's load all the emails:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 118,
"metadata": {},
"outputs": [],
"source": [
"ham_filenames = [f for f in sorted(ham_dir.iterdir()) if len(f.name) > 20]\n",
"spam_filenames = [f for f in sorted(spam_dir.iterdir()) if len(f.name) > 20]"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 119,
"metadata": {},
"outputs": [],
"source": [
"len(ham_filenames)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 120,
"metadata": {},
"outputs": [],
"source": [
"len(spam_filenames)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use Python's `email` module to parse these emails (this handles headers, encoding, and so on):"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 121,
"metadata": {},
"outputs": [],
"source": [
"import email\n",
"import email.policy\n",
"\n",
"def load_email(filepath):\n",
" with open(filepath, \"rb\") as f:\n",
" return email.parser.BytesParser(policy=email.policy.default).parse(f)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 122,
"metadata": {},
"outputs": [],
"source": [
"ham_emails = [load_email(filepath) for filepath in ham_filenames]\n",
"spam_emails = [load_email(filepath) for filepath in spam_filenames]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at one example of ham and one example of spam, to get a feel of what the data looks like:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 123,
"metadata": {},
"outputs": [],
"source": [
"print(ham_emails[1].get_content().strip())"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 124,
"metadata": {},
"outputs": [],
"source": [
"print(spam_emails[6].get_content().strip())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some emails are actually multipart, with images and attachments (which can have their own attachments). Let's look at the various types of structures we have:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 125,
"metadata": {},
"outputs": [],
"source": [
"def get_email_structure(email):\n",
" if isinstance(email, str):\n",
" return email\n",
" payload = email.get_payload()\n",
" if isinstance(payload, list):\n",
" return \"multipart({})\".format(\", \".join([\n",
" get_email_structure(sub_email)\n",
" for sub_email in payload\n",
" ]))\n",
" else:\n",
" return email.get_content_type()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 126,
"metadata": {},
"outputs": [],
"source": [
"from collections import Counter\n",
2017-10-04 10:57:40 +02:00
"\n",
"def structures_counter(emails):\n",
" structures = Counter()\n",
" for email in emails:\n",
" structure = get_email_structure(email)\n",
" structures[structure] += 1\n",
" return structures"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 127,
"metadata": {},
"outputs": [],
"source": [
"structures_counter(ham_emails).most_common()"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 128,
"metadata": {},
"outputs": [],
"source": [
"structures_counter(spam_emails).most_common()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2018-01-22 21:08:12 +01:00
"It seems that the ham emails are more often plain text, while spam has quite a lot of HTML. Moreover, quite a few ham emails are signed using PGP, while no spam is. In short, it seems that the email structure is useful information to have."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's take a look at the email headers:"
2016-09-27 23:31:21 +02:00
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 129,
"metadata": {},
"outputs": [],
"source": [
"for header, value in spam_emails[0].items():\n",
" print(header,\":\",value)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There's probably a lot of useful information in there, such as the sender's email address (12a1mailbot1@web.de looks fishy), but we will just focus on the `Subject` header:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 130,
"metadata": {},
"outputs": [],
"source": [
"spam_emails[0][\"Subject\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, before we learn too much about the data, let's not forget to split it into a training set and a test set:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 131,
"metadata": {},
2016-09-27 23:31:21 +02:00
"outputs": [],
"source": [
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
2020-11-21 00:22:42 +01:00
"X = np.array(ham_emails + spam_emails, dtype=object)\n",
"y = np.array([0] * len(ham_emails) + [1] * len(spam_emails))\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n",
" random_state=42)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, let's start writing the preprocessing functions. First, we will need a function to convert HTML to plain text. Arguably the best way to do this would be to use the great [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/) library, but I would like to avoid adding another dependency to this project, so let's hack a quick & dirty solution using regular expressions (at the risk of [un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment](https://stackoverflow.com/a/1732454/38626)). The following function first drops the `<head>` section, then converts all `<a>` tags to the word HYPERLINK, then it gets rid of all HTML tags, leaving only the plain text. For readability, it also replaces multiple newlines with single newlines, and finally it unescapes html entities (such as `&gt;` or `&nbsp;`):"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 132,
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"from html import unescape\n",
"\n",
"def html_to_plain_text(html):\n",
" text = re.sub('<head.*?>.*?</head>', '', html, flags=re.M | re.S | re.I)\n",
" text = re.sub('<a\\s.*?>', ' HYPERLINK ', text, flags=re.M | re.S | re.I)\n",
" text = re.sub('<.*?>', '', text, flags=re.M | re.S)\n",
" text = re.sub(r'(\\s*\\n)+', '\\n', text, flags=re.M | re.S)\n",
" return unescape(text)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see if it works. This is HTML spam:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 133,
"metadata": {},
"outputs": [],
"source": [
"html_spam_emails = [email for email in X_train[y_train==1]\n",
" if get_email_structure(email) == \"text/html\"]\n",
"sample_html_spam = html_spam_emails[7]\n",
"print(sample_html_spam.get_content().strip()[:1000], \"...\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And this is the resulting plain text:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 134,
"metadata": {},
"outputs": [],
"source": [
"print(html_to_plain_text(sample_html_spam.get_content())[:1000], \"...\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great! Now let's write a function that takes an email as input and returns its content as plain text, whatever its format is:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 135,
"metadata": {},
"outputs": [],
"source": [
"def email_to_text(email):\n",
" html = None\n",
" for part in email.walk():\n",
" ctype = part.get_content_type()\n",
" if not ctype in (\"text/plain\", \"text/html\"):\n",
" continue\n",
" try:\n",
" content = part.get_content()\n",
" except: # in case of encoding issues\n",
" content = str(part.get_payload())\n",
" if ctype == \"text/plain\":\n",
" return content\n",
" else:\n",
" html = content\n",
" if html:\n",
" return html_to_plain_text(html)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 136,
"metadata": {},
"outputs": [],
"source": [
"print(email_to_text(sample_html_spam)[:100], \"...\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's throw in some stemming! We will use the Natural Language Toolkit ([NLTK](http://www.nltk.org/)):"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 137,
"metadata": {},
"outputs": [],
"source": [
"import nltk\n",
"\n",
"stemmer = nltk.PorterStemmer()\n",
"for word in (\"Computations\", \"Computation\", \"Computing\", \"Computed\", \"Compute\",\n",
" \"Compulsive\"):\n",
" print(word, \"=>\", stemmer.stem(word))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will also need a way to replace URLs with the word \"URL\". For this, we could use hard core [regular expressions](https://mathiasbynens.be/demo/url-regex) but we will just use the [urlextract](https://github.com/lipoja/URLExtract) library:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 138,
"metadata": {},
"outputs": [],
"source": [
"# Is this notebook running on Colab or Kaggle?\n",
"IS_COLAB = \"google.colab\" in sys.modules\n",
"IS_KAGGLE = \"kaggle_secrets\" in sys.modules\n",
"\n",
2021-05-25 02:07:29 +02:00
"# if running this notebook on Colab or Kaggle, we just pip install urlextract\n",
"if IS_COLAB or IS_KAGGLE:\n",
" %pip install -q -U urlextract"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** inside a Jupyter notebook, always use `%pip` instead of `!pip`, as `!pip` may install the library inside the wrong environment, while `%pip` makes sure it's installed inside the currently running environment."
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 139,
"metadata": {},
"outputs": [],
"source": [
"import urlextract # may require an Internet connection to download root domain\n",
" # names\n",
"\n",
"url_extractor = urlextract.URLExtract()\n",
"some_text = \"Will it detect github.com and https://youtu.be/7Pq-S557XQU?t=3m32s\"\n",
"print(url_extractor.find_urls(some_text))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are ready to put all this together into a transformer that we will use to convert emails to word counters. Note that we split sentences into words using Python's `split()` method, which uses whitespaces for word boundaries. This works for many written languages, but not all. For example, Chinese and Japanese scripts generally don't use spaces between words, and Vietnamese often uses spaces even between syllables. It's okay in this exercise, because the dataset is (mostly) in English."
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 140,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.base import BaseEstimator, TransformerMixin\n",
"\n",
"class EmailToWordCounterTransformer(BaseEstimator, TransformerMixin):\n",
" def __init__(self, strip_headers=True, lower_case=True,\n",
" remove_punctuation=True, replace_urls=True,\n",
" replace_numbers=True, stemming=True):\n",
" self.strip_headers = strip_headers\n",
" self.lower_case = lower_case\n",
" self.remove_punctuation = remove_punctuation\n",
" self.replace_urls = replace_urls\n",
" self.replace_numbers = replace_numbers\n",
" self.stemming = stemming\n",
" def fit(self, X, y=None):\n",
" return self\n",
" def transform(self, X, y=None):\n",
" X_transformed = []\n",
" for email in X:\n",
" text = email_to_text(email) or \"\"\n",
" if self.lower_case:\n",
" text = text.lower()\n",
" if self.replace_urls and url_extractor is not None:\n",
" urls = list(set(url_extractor.find_urls(text)))\n",
" urls.sort(key=lambda url: len(url), reverse=True)\n",
" for url in urls:\n",
" text = text.replace(url, \" URL \")\n",
" if self.replace_numbers:\n",
" text = re.sub(r'\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?', 'NUMBER', text)\n",
" if self.remove_punctuation:\n",
" text = re.sub(r'\\W+', ' ', text, flags=re.M)\n",
" word_counts = Counter(text.split())\n",
" if self.stemming and stemmer is not None:\n",
" stemmed_word_counts = Counter()\n",
" for word, count in word_counts.items():\n",
" stemmed_word = stemmer.stem(word)\n",
" stemmed_word_counts[stemmed_word] += count\n",
" word_counts = stemmed_word_counts\n",
" X_transformed.append(word_counts)\n",
" return np.array(X_transformed)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try this transformer on a few emails:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 141,
"metadata": {},
"outputs": [],
"source": [
"X_few = X_train[:3]\n",
"X_few_wordcounts = EmailToWordCounterTransformer().fit_transform(X_few)\n",
"X_few_wordcounts"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This looks about right!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we have the word counts, and we need to convert them to vectors. For this, we will build another transformer whose `fit()` method will build the vocabulary (an ordered list of the most common words) and whose `transform()` method will use the vocabulary to convert word counts to vectors. The output is a sparse matrix."
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 142,
"metadata": {},
"outputs": [],
"source": [
"from scipy.sparse import csr_matrix\n",
"\n",
"class WordCounterToVectorTransformer(BaseEstimator, TransformerMixin):\n",
" def __init__(self, vocabulary_size=1000):\n",
" self.vocabulary_size = vocabulary_size\n",
" def fit(self, X, y=None):\n",
" total_count = Counter()\n",
" for word_count in X:\n",
" for word, count in word_count.items():\n",
" total_count[word] += min(count, 10)\n",
" most_common = total_count.most_common()[:self.vocabulary_size]\n",
" self.vocabulary_ = {word: index + 1\n",
" for index, (word, count) in enumerate(most_common)}\n",
" return self\n",
" def transform(self, X, y=None):\n",
" rows = []\n",
" cols = []\n",
" data = []\n",
" for row, word_count in enumerate(X):\n",
" for word, count in word_count.items():\n",
" rows.append(row)\n",
" cols.append(self.vocabulary_.get(word, 0))\n",
" data.append(count)\n",
" return csr_matrix((data, (rows, cols)),\n",
" shape=(len(X), self.vocabulary_size + 1))"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 143,
"metadata": {},
"outputs": [],
"source": [
"vocab_transformer = WordCounterToVectorTransformer(vocabulary_size=10)\n",
"X_few_vectors = vocab_transformer.fit_transform(X_few_wordcounts)\n",
"X_few_vectors"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 144,
"metadata": {},
"outputs": [],
"source": [
"X_few_vectors.toarray()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What does this matrix mean? Well, the 99 in the second row, first column, means that the second email contains 99 words that are not part of the vocabulary. The 11 next to it means that the first word in the vocabulary is present 11 times in this email. The 9 next to it means that the second word is present 9 times, and so on. You can look at the vocabulary to know which words we are talking about. The first word is \"the\", the second word is \"of\", etc."
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 145,
"metadata": {},
"outputs": [],
"source": [
"vocab_transformer.vocabulary_"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are now ready to train our first spam classifier! Let's transform the whole dataset:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 146,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.pipeline import Pipeline\n",
"\n",
"preprocess_pipeline = Pipeline([\n",
" (\"email_to_wordcount\", EmailToWordCounterTransformer()),\n",
" (\"wordcount_to_vector\", WordCounterToVectorTransformer()),\n",
"])\n",
"\n",
"X_train_transformed = preprocess_pipeline.fit_transform(X_train)"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 147,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.model_selection import cross_val_score\n",
"\n",
"log_clf = LogisticRegression(max_iter=1000, random_state=42)\n",
"score = cross_val_score(log_clf, X_train_transformed, y_train, cv=3)\n",
"score.mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2020-11-21 00:22:42 +01:00
"Over 98.5%, not bad for a first try! :) However, remember that we are using the \"easy\" dataset. You can try with the harder datasets, the results won't be so amazing. You would have to try multiple models, select the best ones and fine-tune them using cross-validation, and so on.\n",
"\n",
"But you get the picture, so let's stop now, and just print out the precision/recall we get on the test set:"
]
},
{
"cell_type": "code",
2021-10-30 21:28:30 +02:00
"execution_count": 148,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import precision_score, recall_score\n",
"\n",
"X_test_transformed = preprocess_pipeline.transform(X_test)\n",
"\n",
"log_clf = LogisticRegression(max_iter=1000, random_state=42)\n",
"log_clf.fit(X_train_transformed, y_train)\n",
"\n",
"y_pred = log_clf.predict(X_test_transformed)\n",
"\n",
"print(\"Precision: {:.2f}%\".format(100 * precision_score(y_test, y_pred)))\n",
"print(\"Recall: {:.2f}%\".format(100 * recall_score(y_test, y_pred)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
2016-05-22 17:40:18 +02:00
}
],
"metadata": {
"kernelspec": {
2021-10-29 07:03:30 +02:00
"display_name": "Python 3",
2016-05-22 17:40:18 +02:00
"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",
2021-10-17 03:27:34 +02:00
"version": "3.8.12"
2016-05-22 17:40:18 +02:00
},
2016-09-27 23:31:21 +02:00
"nav_menu": {},
2016-05-22 17:40:18 +02:00
"toc": {
2016-09-27 23:31:21 +02:00
"navigate_menu": true,
"number_sections": true,
"sideBar": true,
"threshold": 6,
2016-05-22 17:40:18 +02:00
"toc_cell": false,
2016-09-27 23:31:21 +02:00
"toc_section_display": "block",
2016-05-22 17:40:18 +02:00
"toc_window_display": false
}
},
"nbformat": 4,
2020-04-06 09:13:12 +02:00
"nbformat_minor": 4
2016-05-22 17:40:18 +02:00
}