{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Load the Iris Dataset\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "#Load CSV files\n",
    "inputs_train=pd.read_csv('datasets/iris_train.csv',usecols = [0,1,2,3],skiprows = None,header=None).values\n",
    "labels_train = pd.read_csv('datasets/iris_train.csv',usecols = [4],skiprows = None ,header=None).values.reshape(-1)\n",
    "inputs_test=pd.read_csv('datasets/iris_test.csv',usecols = [0,1,2,3],skiprows = None,header=None).values\n",
    "labels_test = pd.read_csv('datasets/iris_test.csv',usecols = [4],skiprows = None ,header=None).values.reshape(-1)\n",
    "\n",
    "#print(\"Data loaded\")\n",
    "#print(\"Train set inputs:\",inputs_train)\n",
    "#print(\"Train set labels:\",labels_train)\n",
    "#print(\"Test set inputs:\",inputs_test)\n",
    "#print(\"Test set labels:\",labels_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Build the neural network"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_26\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " dense_78 (Dense)            (None, 20)                100       \n",
      "                                                                 \n",
      " dense_79 (Dense)            (None, 20)                420       \n",
      "                                                                 \n",
      " dense_80 (Dense)            (None, 3)                 63        \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 583\n",
      "Trainable params: 583\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "\n",
    "k_l2=0\n",
    "\n",
    "keras_model = tf.keras.Sequential([\n",
    "    tf.keras.layers.Dense(20, activation='tanh',kernel_regularizer=keras.regularizers.l2(k_l2)),\n",
    "    tf.keras.layers.Dense(20, activation='tanh',kernel_regularizer=keras.regularizers.l2(k_l2)),\n",
    "    tf.keras.layers.Dense(3, activation='softmax',kernel_regularizer=keras.regularizers.l2(k_l2))\n",
    "])\n",
    "\n",
    "keras_model.build(input_shape=[None,4])\n",
    "keras_model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Train the neural network"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "keras_model.compile(\n",
    "    optimizer=tf.keras.optimizers.Adam(), # Optimizer\n",
    "    loss=tf.keras.losses.SparseCategoricalCrossentropy(), # Loss function to minimize\n",
    "    metrics=[keras.metrics.SparseCategoricalAccuracy()] # List of metrics to monitor\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training started ..\n",
      "Training finished.\n"
     ]
    }
   ],
   "source": [
    "# Train loop\n",
    "\n",
    "print(\"Training started ..\")\n",
    "\n",
    "history = keras_model.fit(\n",
    "    inputs_train,\n",
    "    labels_train,\n",
    "    batch_size=len(inputs_train),\n",
    "    epochs=2000,\n",
    "    validation_data=(inputs_test, labels_test),\n",
    "    verbose=0\n",
    ")\n",
    "\n",
    "print(\"Training finished.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 34572 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "plt.plot(history.history[\"loss\"],label=\"train\")\n",
    "plt.plot(history.history[\"val_loss\"],label=\"test\")\n",
    "plt.xlabel(\"Iteration\")\n",
    "plt.ylabel('Cross-Entropy Loss')\n",
    "plt.grid()\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 27900 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#print(\"history\",history.history)\n",
    "plt.plot(history.history['sparse_categorical_accuracy'],label=\"train\")\n",
    "plt.plot(history.history['val_sparse_categorical_accuracy'],label=\"validation\")\n",
    "plt.title('Model Accuracy')\n",
    "#plt.yscale('log')\n",
    "plt.ylabel('Acc')\n",
    "plt.xlabel('Iteration')\n",
    "plt.grid()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Save the trained model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: IrisModel/assets\n"
     ]
    }
   ],
   "source": [
    "keras_model.save(\"IrisModel\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Check we can re-load our saved model back in\n",
    "- And check it still works (we will print its accuracy on the test set!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_26\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " dense_78 (Dense)            (None, 20)                100       \n",
      "                                                                 \n",
      " dense_79 (Dense)            (None, 20)                420       \n",
      "                                                                 \n",
      " dense_80 (Dense)            (None, 3)                 63        \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 583\n",
      "Trainable params: 583\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "Accuracy of saved model on test set 0.96666664\n"
     ]
    }
   ],
   "source": [
    "model2 = keras.models.load_model('IrisModel') # just need to give it a folder name here.\n",
    "model2.summary()\n",
    "predictions=model2(inputs_test)\n",
    "accuracy_metric=keras.metrics.SparseCategoricalAccuracy()\n",
    "print(\"Accuracy of saved model on test set\",accuracy_metric(labels_test,predictions).numpy())"
   ]
  }
 ],
 "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.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
