{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "mpl.rcParams['font.size'] = 14"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "seed = 1\n",
    "N = 200\n",
    "K = 5\n",
    "r_high = 5\n",
    "rmin,rmax = -r_high, r_high"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kerasy.utils import generateWholeCakes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 16808 characters]\n",
      "text/plain": [
       "<Figure size 288x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "train_x, train_y = generateWholeCakes(K, N, r_high=r_high, seed=seed, same=False, plot=True, figsize=(4,4), noise_scale=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Decision Tree"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kerasy.ML.tree import DecisionTreeClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "X,Y = np.meshgrid(np.linspace(rmin,rmax,100), np.linspace(rmin,rmax,100))\n",
    "XY = np.c_[X.ravel(),Y.ravel()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 298532 characters]\n",
      "text/plain": [
       "<Figure size 1008x576 with 6 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(14,8))\n",
    "depths = [1,2,3,5,7,9]\n",
    "accuracies = []\n",
    "for i, depth in enumerate(depths):\n",
    "    ax = fig.add_subplot(2,3,i+1)\n",
    "    # Change the depth to fit the data.\n",
    "    model = DecisionTreeClassifier(criterion=\"gini\", max_depth=depth, random_state=seed)\n",
    "    model.fit(train_x, train_y)\n",
    "    predictions = model.predict(train_x)\n",
    "    accuracy = np.mean(predictions==train_y)\n",
    "    accuracies.append(accuracy)\n",
    "    Z = model.predict(XY).reshape(X.shape)\n",
    "    ax.scatter(train_x[:,0], train_x[:,1], c=train_y, s=50)\n",
    "    ax.pcolor(X,Y,Z,alpha=0.2)\n",
    "    ax.set_title(f\"Decision Tree max depth={model.max_depth}\\naccuracy: {100*accuracy:.3f}%\"), ax.set_xlim(rmin,rmax), ax.set_ylim(rmin,rmax)\n",
    "    ax.set_xticks([]), ax.set_yticks([])\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 19288 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(depths, accuracies, color=\"red\")\n",
    "plt.scatter(depths, accuracies, color=\"red\")\n",
    "plt.title(\"The relationship between\\nmax_depth and accuracy\"), plt.grid() \n",
    "plt.xlabel(\"max depths\"), plt.xticks(depths), \n",
    "plt.ylabel(\"accuracy\"), plt.ylim(0,1)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_depth = 5\n",
    "model = DecisionTreeClassifier(criterion=\"gini\", max_depth=best_depth, random_state=seed)\n",
    "model.fit(train_x, train_y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### `graphviz`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "fn = f\"decision_tree_max_depth{best_depth}.png\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.export_graphviz(fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "![decision_tree_graphvis](decision_tree_max_depth5.png)\n"
     ]
    }
   ],
   "source": [
    "print(f\"![decision_tree_graphvis]({fn})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![decision_tree_graphvis](decision_tree_max_depth5.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "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.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
