{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "30b61190-61c1-4dd2-a9ec-acbadc8a52ef",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Distance function usage demonstration on a synthetic dataset\n",
    "Goal of the excercise is to code Euclidean distance on your own and apply it to the NumPy matrix containing n-dimensional vectors (data points) in an Euclidean space as a rows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a70c5553-ad01-4d43-93fb-50c085f09a64",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "import math"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d685ada-68b5-474a-84d5-5bfacd4a9eca",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Calculating distances between data points using Euclidean distance\n",
    "\n",
    "- Load data points from 'data_points.csv' into the Pandas DataFrame and save the raw NumPy array to the *data* variable using *values* property\n",
    "- Check calculated distances from table\n",
    "- Hint: set index_col to proper value in case that the data are not loaded correctly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b9043cd-4e41-40b0-93e1-712d94d122b3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c613d1a9-5f9e-43bd-aba5-a21b5a5218a4",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "01955cd6-d35d-4b96-81a6-94ab90efce5c",
   "metadata": {},
   "source": [
    "## Implement the *euclid_distance* function which takes two NumPy arrays as an input and return the distance between these two vectors\n",
    "- Test the function on the first two rows of the matrix afterwards\n",
    "    - Result = 6.429660566468498"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "077896be-06fe-4136-82f2-960fa41d178e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def euclid_distance(x, y):\n",
    "    assert x.size == y.size\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d32df8f7-525a-4eaf-92a9-bde2b384972a",
   "metadata": {},
   "outputs": [],
   "source": [
    "euclid_distance(data[0], data[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c70a937-3966-4657-859b-2b96ceb46b21",
   "metadata": {},
   "source": [
    "## Compute the distance matrix for the input data\n",
    "- Elements of the matrix contain the distances between every two vectors of the input data\n",
    "    - What is the shape of this matrix?\n",
    "    - Does the matrix have some properties which you can guess prior to the constructing such matrix?\n",
    "    - [np.zeros](https://numpy.org/doc/stable/reference/generated/numpy.zeros.html) might render useful"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4b7b175-34f5-488c-be43-330cf01ced75",
   "metadata": {},
   "outputs": [],
   "source": [
    "n_points = data.shape[0]\n",
    "distance_matrix = None\n",
    "\n",
    "# Your code\n",
    "\n",
    "distance_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9dd298e2-c2af-46b4-9865-24d675c3fe2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i, j in [(0,1), (1,0), (1,1), (0,2), (0,3), (0,4), (0,5),(22,2),(42, 34), (97, 81)]:\n",
    "    print(f'|{i}|{j}|{round(distance_matrix[i, j], 3)}|')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdf2f8ad-3890-4c72-9611-f29a66c18e46",
   "metadata": {},
   "source": [
    "|Point1|Point2|Euclidean distance|\n",
    "|:-------|:-------|:--------|\n",
    "|0|1|6.43|\n",
    "|1|0|6.43|\n",
    "|1|1|0.0|\n",
    "|0|2|12.301|\n",
    "|0|3|12.365|\n",
    "|0|4|10.825|\n",
    "|0|5|12.771|\n",
    "|22|2|9.682|\n",
    "|42|34|8.195|\n",
    "|97|81|4.927|\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c877b5c7-60df-4d84-8b1a-9412b0c1cd53",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Continue with only 2 dimensional data\n",
    "- Restrict our data to only first two dimensions, i.e. columns\n",
    "- Calculate distance matrix for these points\n",
    "- Visualize the data points\n",
    "- Select one point and its epsilon neigborhood based on the values in a distance matrix and distinguish the selected points with color (select point 83 and use eps value 1.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76e314db-9b52-4e0c-979c-f735bb1e398a",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_2d = df.iloc[:, :2].copy()\n",
    "df_2d.columns = ['x', 'y']\n",
    "df_2d.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b5fd979-0e36-4ea3-9567-d22eb5d5c792",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = df_2d.values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f05a805c-6b89-4a6b-95b7-777438fe989e",
   "metadata": {},
   "outputs": [],
   "source": [
    "n_points = data.shape[0]\n",
    "distance_matrix = None\n",
    "\n",
    "# Your code\n",
    "\n",
    "distance_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ead9931-dced-4f90-8a71-f6bfd8cf9695",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(data=df_2d, x='x', y='y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05cc3e09-5d3f-487a-b8c0-2caf7fb0b960",
   "metadata": {},
   "outputs": [],
   "source": [
    "selected_point_id = 83\n",
    "df_2d['mark'] = 'points'\n",
    "df_2d.loc[selected_point_id, 'mark'] = 'selected'\n",
    "\n",
    "sns.scatterplot(data=df_2d, x='x', y='y', hue='mark')\n",
    "plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11c86849-2b27-40a0-8867-32c58d0c4afb",
   "metadata": {},
   "outputs": [],
   "source": [
    "eps = 1.5\n",
    "np.where(distance_matrix[selected_point_id, :] < eps)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05edf34c-0925-4b8a-ade2-51da2aa3096a",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(6,6))\n",
    "\n",
    "## Mark the selected points in the *mark* attribute\n",
    "\n",
    "sns.scatterplot(data=df_2d, x='x', y='y', hue='mark')\n",
    "plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e94b5d88-1743-465d-a8ce-5b8198b8adaf",
   "metadata": {},
   "source": [
    "# One Rule Classifier implementation\n",
    "- Load the *tennis.csv* into the Pandas CSV\n",
    "- Implement the classification algorithm that generates one rule for each predictor in the data, then selects the rule with the smallest total error as its \"one rule\".\n",
    "- Beware the fact that \"ONE rule\" it meant as a rule-set for ONE feature, i.e. there will be multiple rules created\n",
    "- Find the rule-set with lowest error rate and print both error and rule-set\n",
    "- You can take a look at [this website](https://www.saedsayad.com/oner.htm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa78a953-9074-43a3-baf3-9108b7b11810",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis = pd.read_csv('tennis.csv')\n",
    "tennis"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2b16f59-3ea7-4d01-bc05-dd52c92ad40e",
   "metadata": {},
   "source": [
    "## Try to compute error for a given rules\n",
    "- IF outlook == sunny THEN play = yes\n",
    "- IF outlook == sunny THEN play = no\n",
    "- Which one is better?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "533e3da3-4067-4d39-b1b8-680ab6c12600",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[tennis['outlook'] == 'sunny']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c11e3e9-e1ed-401e-9e70-678ebb39174e",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[tennis['outlook'] == 'sunny'].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "411eb2e4-daad-4d10-b2ed-05e7cc7eb69d",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'yes')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9868e8c3-e393-496b-9537-e71a3bf08102",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'yes')].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfa4c293-21af-4d6f-ba31-8f6c5d0bc971",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Error rate for the play = yes\n",
    "- 3/5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cca9d026-401a-4545-86b5-60b681455828",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'yes')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "068e97ed-b5cc-4713-b174-4add46b6d524",
   "metadata": {},
   "outputs": [],
   "source": [
    "(tennis.loc[tennis['outlook'] == 'sunny'].shape[0] - tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'yes')].shape[0]) / tennis.loc[tennis['outlook'] == 'sunny'].shape[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5efb62b-be17-40de-9150-7ce4497f8002",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Error rate for the play = no\n",
    "- 2/5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0783a6aa-91c8-4997-824c-96600424fc5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'no')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38be2fec-bbfb-4e8d-9246-d7bda171bea9",
   "metadata": {},
   "outputs": [],
   "source": [
    "(tennis.loc[tennis['outlook'] == 'sunny'].shape[0] - tennis.loc[(tennis['outlook'] == 'sunny') & (tennis['play'] == 'no')].shape[0]) / tennis.loc[tennis['outlook'] == 'sunny'].shape[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09cead52-2376-43db-ad78-fd6903939b09",
   "metadata": {
    "tags": []
   },
   "source": [
    "## How to compute the total error rate for an attribute?\n",
    "- It's just a fraction with sum the partaial number of errors of the individual rules as a nominator and number of rows as a denominator :-)\n",
    "- e.g. 5/14 for the Temperature-related rules\n",
    "\n",
    "Hint: How to get just an unique values of a given feature? Just use *.unique()* method from Pandas\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08e9fe17-5c35-4cba-b4eb-7f8d827eb4e6",
   "metadata": {},
   "source": [
    "# Implement the 1R classifier in your code and print the best rule-set\n",
    "- Example output:\n",
    "~~~\n",
    "IF outlook == sunny THEN play = no\n",
    "IF outlook == overcast THEN play = yes\n",
    "IF outlook == rainy THEN play = yes\n",
    "~~~"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e08f77a3-6e65-48ff-84e8-4157ca9f1f91",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "4a65dc8f-cb95-40d7-ba81-c779df06e77b",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Tasks\n",
    "## Task 1 (1p)\n",
    "1. Load the data points from *'data_points_grid.csv'*\n",
    "2. Create function for Manhattan distance calculation - you can see [this](https://en.wikipedia.org/wiki/Taxicab_geometry)\n",
    "3. Use Manhattan distance for the distance matrix calculation\n",
    "- Select point on index **421**, calculate its neighborhood points with eps <= 1.5\n",
    "- Visualize the result\n",
    "4. Use Euclidean distance for the distance matrix calculation\n",
    "- Select point on index **421**, calculate its neighborhood points with eps <= 1.5\n",
    "- Visualize the result\n",
    "\n",
    "**Describe the differences you see for both of the images in a Markdown cell!**\n",
    "\n",
    "#### Optional\n",
    "- Repeat the process for 2-Dimensional random data used during excersice. \n",
    "- Use Manhattan distance instead of Euclidean. Do you see any difference?\n",
    "\n",
    "## Task 2 (1p)\n",
    "- Finish the Single-rule (1R) classifier implementation\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af3a8fb2-4b30-4258-80ae-9e14db3eab89",
   "metadata": {},
   "outputs": [],
   "source": [
    "def manhattan_distance(x, y):\n",
    "    assert x.size == y.size\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52e5a1b2-0243-448f-9d6e-628f562288d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_2d_grid = pd.read_csv('data_points_grid.csv', index_col=0)\n",
    "data = df_2d_grid.values\n",
    "df_2d_grid.head()"
   ]
  }
 ],
 "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.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
