{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# IN3050/IN4050 2023: Week 05 Classification by *k*NN\n",
    "## Introduction\n",
    "The goal of this week is to get a first experience with supervised classification.\n",
    "In particular, we will get familiar with how to set up, run and evaluate experiments.\n",
    "We will also implement the *k*NN-algorithm using pure python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import sklearn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "To do machine learning, we need data.\n",
    "To make it simple, we use scikit-learn to construct a synthetic dataset with\n",
    "- 2 classes\n",
    "- 2 numerical features\n",
    "- 200 items\n",
    "\n",
    "We will use `X`-s for the input values and `t`-s for the target values. Since we will be using pure python in this exercise set, we transform the data from numpy arrays, like `X_np`, to lists, like `X1`.\n",
    "\n",
    "Don't worry about the magic recipe for how we cook the data for now!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import make_blobs\n",
    "X_np, t_np = make_blobs(n_samples=200, centers=[[0,0],[1,2]], \n",
    "                  n_features=2, random_state=2019)\n",
    "X1 = [(X_np[i,0], X_np[i,1]) for i in range(X_np.shape[0])]\n",
    "t1 = [t_np[i] for i in range(X_np.shape[0])]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a general form for representing data we will use a lot in this course. We store the features in one list and the labels in another list of the same length. For example, y[14] is the label the dataset ascribes to the input X[14], where X[14] is a pair (two-tuple) of numbers.\n",
    "\n",
    "(Later on we will use numpy arrays and not lists, e.g., the X_np, t_np, above.)\n",
    "\n",
    "We can then take a look at the training set using scatterplot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(X_np[:, 0], X_np[:, 1], c=t_np)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To add a legend (i.e., naming the classes) we sort the data into the two classes before plotting. We may then use the `plot` command."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show(X, y, marker='.'):\n",
    "    labels = set(y)\n",
    "    cl = {lab : [] for lab in labels}\n",
    "    # cl[lab] shall contain the datapoints labeled lab\n",
    "    for (a, b) in zip(X, y):\n",
    "        cl[b].append(a)\n",
    "    for lab in labels:\n",
    "        plt.plot([a[0] for a in cl[lab]], [a[1] for a in cl[lab]], \n",
    "                 marker, label=\"class {}\".format(lab))\n",
    "    plt.legend()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show(X1, t1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## *k*NN\n",
    "We will now implement the *k*NN algorithm.\n",
    "We first need to calculate the distance between two points.\n",
    "\n",
    "There are, of course, methods, e.g. in numpy, that are more than willing to do this for us. But we are here to learn. So we implement it ourselves.\n",
    "\n",
    "### Exercise I: Distance\n",
    "Implement a (L2-) distance function. It should work for points in *n*-dimensional space for any integer *n*>0. Check that dist((3,4,0),(0,0,12)) is 13."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def distance_L2(a,b):\n",
    "    \"Calculate and return the L2-distance between a and b\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert distance_L2((3,4,0),(0,0,12)) == 13"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise II: Majority class\n",
    "The next thing we need is a way to determine the majority class from a set of votes. Implement a procedure which takes a list as argument and returns the majority class. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def majority(a):\n",
    "    \"\"\"Return the majority class of a\n",
    "    \n",
    "    For example majority([0,1,1,1,0]) should return 1\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Hint: Counter\n",
    "For this we can use the Counter method. If you are not familiar with Counter, experiment with it to see how it works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "print(\"Example\")\n",
    "s = ['a', 'b', 'c', 'b', 'c']\n",
    "counts = Counter(s)\n",
    "print(s)\n",
    "print(counts)\n",
    "print(counts.most_common())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise III: the *k*NN algorithm\n",
    "We will use a class for implementing the classifier. We have chosen a format that we can later reuse for various other classifier algorithms. The format is inspired by scikit-learn. We will have a superclass where we can put methods common to the various classification algorithms.\n",
    "\n",
    "The class will have three methods; one `init` where we set the hypermarameters, one `fit` where the training takes place, and one `predict` which predicts the class of a list of new items after we have trained the classifier.\n",
    "\n",
    "The training will have the form\n",
    "```python\n",
    "cls = PykNNClassifier(k=5) # OR some other number, default 3\n",
    "cls.fit(X_train, t_train)\n",
    "```\n",
    "\n",
    "We can then classify a new item by e.g.\n",
    "```python\n",
    "p = (1,1)\n",
    "cls.predict([p])\n",
    "```\n",
    "\n",
    "Implement the `predict` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PyClassifier():\n",
    "    \"\"\"Common methods to all python classifiers --- if any\n",
    "    \n",
    "    Nothing here yet\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PykNNClassifier(PyClassifier):\n",
    "    \"\"\"kNN classifier using pure python representations\"\"\"\n",
    "    \n",
    "    def __init__(self, k=3, dist=distance_L2):\n",
    "        self.k = k\n",
    "        self.dist = dist\n",
    "        \n",
    "    def fit(self, X_train, t_train):\n",
    "        self.X_train = X_train\n",
    "        self.t_train = t_train\n",
    "    \n",
    "    def predict(self, a):\n",
    "        \"\"\"Implement this\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Experiments and evaluation\n",
    "To check how good the classifier is, we cannot consider singular datapoints. \n",
    "We have to see how the classifier performs on a larger test set.\n",
    "With our synthetic training data, we can make a test set in a similar way.\n",
    "\n",
    "We follow the same recipe as for the training set, but observe that we use a different *random_state* to get a set different from the training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_np, t_np = make_blobs(n_samples=200, centers=[[0,0],[1,2]], \n",
    "                  n_features=2, random_state=2020)\n",
    "X2 = [(X_np[i,0], X_np[i,1]) for i in range(X_np.shape[0])]\n",
    "t2 = [t_np[i] for i in range(X_np.shape[0])]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "show(X2, t2, 'x')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise IV: Accuracy\n",
    "There are several different evaluation measures that can be used, and we will see a couple of them the coming weeks. For today, we only consider the simple *accuracy*, the proportion of items classified correctly.\n",
    "\n",
    "Implement a function `accuracy()`. It should take two arguments, where each is a list of labels and compare the two and return a numerical value for the accuracy. We will apply it to measure the accuracy of the classifier `cls` as follows:\n",
    "\n",
    "```python\n",
    "accuracy(cls.predict(X_test), t_test)\n",
    "```\n",
    "\n",
    "Test it on X2, t2 when trained on X1, t1 for various values of *k*.\n",
    "Let *k* be any odd integer below 20. Plot the results.\n",
    "\n",
    "Beware that there is no *k* which is the best for all datasets. It varies with the dataset. To decide on the best *k* for a specific dataset, we should use a separate development test set to determine the best *k*. Then we fix this *k* and test on the final test set. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise V: Variation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One should be cautious drawing too strong conclusions from an experiment like this. Check whether you get the same result with a different random test set drawn from the same distribution."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise VI: Confusion matrix\n",
    "\n",
    "Implement a procedure for calculating a confusion matrix for a classifier and try it on one of the runs above"
   ]
  }
 ],
 "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.9.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
