{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-279435259d3d5529",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "# Practical work: Character recognition using scikit-learn\n",
    "\n",
    "**Marc Buffat**, Dpt Mécanique, UCB Lyon 1\n",
    "\n",
    "from [Python Machine Learning Tutorial](https://www.python-course.eu/digits_dataset_neural_network.php) \n",
    "\n",
    "![handwritten digits](Images/handwritten_digit.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-f2bb368d2b71a175",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "# police des titres\n",
    "plt.rc('font', family='serif', size='18')\n",
    "from IPython.display import display,Markdown\n",
    "import sklearn as sk\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "hide_input": false,
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-a4ba8050df9bab2a",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from validation.validation import info_etudiant\n",
    "def printmd(string):\n",
    "    display(Markdown(string))\n",
    "# test si numero étudiant spécifier\n",
    "try: NUMERO_ETUDIANT\n",
    "except NameError: NUMERO_ETUDIANT = None \n",
    "if type(NUMERO_ETUDIANT) is not int :\n",
    "    printmd(\"**ERREUR:** student ID not specified!!!\")\n",
    "    NOM,PRENOM,NUMERO_ETUDIANT=info_etudiant()\n",
    "    #raise AssertionError(\"NUMERO_ETUDIANT non défini\")\n",
    "# parametres spécifiques\n",
    "_uid_    = NUMERO_ETUDIANT\n",
    "np.random.seed(_uid_)\n",
    "printmd(\"**Login student {} {} uid={}**\".format(NOM,PRENOM,_uid_))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-866b135fed703c18",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## Principle of image recognition using AI\n",
    "\n",
    "![digits database IA](Images/digits_database_IA.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-8a7b29d566cb0e01",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## Data base of handwritten digits\n",
    "\n",
    "A low resolution version of this data base is available with scikit-learn.\n",
    "\n",
    "We start by loading the dataset using:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-ffeed85fc77e07f2",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from sklearn import datasets\n",
    "digits = datasets.load_digits()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-9a039d7a6d44386c",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "# information sur la base de données : dataset\n",
    "display(Markdown(digits.DESCR))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-8ea4220d0fd164f9",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Data Base\n",
    "\n",
    "the results is a generalized dictionary : **Bunch** (allowing access to the data using key-words) \n",
    "\n",
    " - exploring the data base\n",
    "     - data (feature) : images of handwritten digits\n",
    "     - results (target) : numerical value: 0,1,2,..9\n",
    "     \n",
    "  the data are numerical images of 8x8 pixels in black and white with 16 gray levels (from 0 to 15) (i.e. using 4 bits). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-ab8c9f2d16f903c7",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "print(type(digits))\n",
    "print(\"clés:\",digits.keys())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-f3dc0c6fe46a50b0",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "Print, in the following cell, the value of the first data and the first results (target) in the data base.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-f9bbefa722ff37bb",
     "locked": false,
     "points": 0,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "print(\"Data:\",digits.data.shape)\n",
    "print(\"Results:\",digits.target.shape)\n",
    "### BEGIN SOLUTION\n",
    "print(\"premiere donnee brute linéaire:\",digits.data[0].shape,type(digits.data[0][0]))\n",
    "print(digits.data[0])\n",
    "print(\"premiere image:\",digits.images[0].shape,type(digits.images[0][0,0]))\n",
    "print(digits.images[0])\n",
    "print(\"premier resultat:\",type(digits.target[0]),digits.target[0])\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-06ab77cf9bb86237",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Display of the images\n",
    "\n",
    "- using `imshow` to display an image\n",
    "- using a written python function `plot_data` to display a series of nmax images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-c384cd0950356ca3",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "plt.imshow(digits.images[0],cmap='binary')\n",
    "plt.title(digits.target[0])\n",
    "plt.axis('off')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-f83a1b522e0f5222",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "def plot_data(data,target,pred=None,nmax=64,titre=None):\n",
    "    '''display the 64 first images of the DB'''\n",
    "    # set up the figure\n",
    "    fig = plt.figure(figsize=(12, 12))  # figure size \n",
    "    if titre is not None: plt.title(titre)\n",
    "    fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n",
    "    # plot the digits: each image is 8x8 pixels\n",
    "    for i in range(nmax):\n",
    "        ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n",
    "        image = data[i].reshape(8,8)\n",
    "        ax.imshow(image, cmap=plt.cm.binary, interpolation='nearest')    \n",
    "        # label the image with the target value\n",
    "        ax.text(0, 7, str(target[i]),color='b')\n",
    "        # and the predicted value\n",
    "        if pred is not None: ax.text(7,7, str(pred[i]),color='r')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-6465179d978e21e5",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "plot_data(digits.data,digits.target,titre=\"data set initial\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-2dab58eb72009bbc",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## Creation of the datasets for the learning phase\n",
    "\n",
    "- data set for the learning phase (learn)\n",
    "- data set for the validation phase (test)\n",
    "\n",
    "split of the database in two sets: 80% for the training set and  20% for the test set using arbitrary split (depending of the student id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-0496d63c05dfaec5",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "res = train_test_split(digits.data, digits.target, \n",
    "                       train_size=0.8,\n",
    "                       test_size=0.2,\n",
    "                       random_state=NUMERO_ETUDIANT)\n",
    "train_data, test_data, train_labels, test_labels = res \n",
    "print(\"dataset training:\",train_data.shape)\n",
    "print(\"dataset test    :\",test_data.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_data(train_data, train_labels,titre=\"data set d'entrainement\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_data(test_data, test_labels,titre=\"data set de test\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-ad4ae08a048bc4bb",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### definition of the data\n",
    "\n",
    "we need to use normalized data as a numpy array\n",
    "\n",
    "   - X_train, y_train\n",
    "   - X_test, y_test\n",
    "   - beware of aliasing (explicit use of the copy function)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-240b153168bc17f7",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "# normalization of the data\n",
    "X_train = None\n",
    "y_train = None\n",
    "X_test  = None\n",
    "y_test  = None\n",
    "### BEGIN SOLUTION\n",
    "X_train = train_data/15.0\n",
    "y_train = train_labels.copy()\n",
    "X_test  = test_data/15.0\n",
    "y_test  = test_labels.copy()\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-7c57cfb63c92a2c4",
     "locked": true,
     "points": 2,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert (X_train.shape == train_data.shape)\n",
    "assert (y_train.shape == train_labels.shape)\n",
    "assert (X_test.shape == test_data.shape)\n",
    "assert (y_test.shape == test_labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-ff8ad28e839c2568",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## Linear model using a linear logistic regression \n",
    "\n",
    "Build of the linear model\n",
    "\n",
    "     scikit learn  linear_model\n",
    "     \n",
    " - model : LogisticRegression\n",
    "\n",
    "Logistic regression, despite its name, is a linear model used for classification rather than regression. In the literature, logistic regression is also known as \"logit regression,\" \"maximum entropy classification\" (MaxEnt), or \"log-linear classifier.\" In this model, the probabilities that describe the possible outcomes of a single trial are modeled using a logistic function.\n",
    "\n",
    "Logistic regression is implemented in LogisticRegression. This implementation can handle binary logistic regression, One-vs-Rest, or multinomial logistic regression, with optional regularization (l1, l2, elastic net, or none).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-9a16b76766e99f04",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Logistic Regression\n",
    "\n",
    "Logistic regression is a statistical method for predicting binary classes. The outcome or target variable is dichotomous in nature, meaning there are only two possible classes. It calculates the probability of an event occurring.\n",
    "\n",
    "This is a specific case of linear regression where the target variable is categorical. It uses a log of the odds as the dependent variable. Logistic regression predicts the probability of a binary event occurring using a logit function.\n",
    "\n",
    "**Equation of a linear regression**\n",
    "\n",
    "$$ z = \\beta_0 +  \\beta_1 X_1 + ... + \\beta_n X_n $$\n",
    "\n",
    "**Sigmoid Function**\n",
    "$$ p = \\frac{1}{1+e^{-z}} $$\n",
    "\n",
    "**Probability for y=1**\n",
    "$$  p = \\frac{1}{1+e^{-(\\beta_0 +  \\beta_1 X_1 + ... + \\beta_n X_n)}}$$ "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-c8c5b6206bc86456",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "Y = np.linspace(-10,10,100)\n",
    "plt.title(\"probabilité Y=1 (sigmoide)\")\n",
    "plt.plot(Y,1./(1+np.exp(-Y)))\n",
    "Y1 = np.linspace(-10,-3,10)\n",
    "plt.plot(Y1,np.zeros(10),'or')\n",
    "plt.plot(-Y1,np.ones(10),'or')\n",
    "plt.xlabel('z(X)');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-d2e9ab92232e6d1e",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "**Note:** Regularization is applied by default, which is common in machine learning but not in traditional statistics. Another advantage of regularization is that it improves numerical stability.\n",
    "\n",
    "**To do:** modify the parameters using the documentation.\n",
    "\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html\n",
    "\n",
    "**parameters**\n",
    "\n",
    "   - max_iter (from 100 to 200) \n",
    "   - normalization of the data\n",
    "   - regularization\n",
    "\n",
    "To do in the two following cells\n",
    "\n",
    "1. Learning of the model with display of the score\n",
    "2. Model testing and analysis of the prediction quality(criteria: accuracy_score, r2_score)\n",
    "  - calculation of y_pred and accuracy  (prediction rate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-0213c19cca459f9f",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "import sklearn.linear_model\n",
    "\n",
    "model=None\n",
    "### BEGIN SOLUTION\n",
    "model = sklearn.linear_model.LogisticRegression(penalty='l2',max_iter=200)\n",
    "model = model.fit(X_train,y_train)\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-c6a4ecbcf3154cab",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(model.score(X_train,y_train))\n",
    "print(\"score=\",model.score(X_train,y_train))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-a66d1fa8f74e7d7d",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score,r2_score\n",
    "\n",
    "y_pred = None\n",
    "accuracy = None\n",
    "### BEGIN SOLUTION\n",
    "y_pred=model.predict(X_test) \n",
    "print(\"predictions:\\n\",y_pred)\n",
    "accuracy=accuracy_score(y_pred,y_test)\n",
    "print(\"taux de prediction {:3d}%\".format(int(accuracy*100)))\n",
    "print(\"R2 score  {:.2f}\".format(r2_score(y_test, y_pred)))\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-874ba10338ea2166",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(len(y_test) == len(y_pred))\n",
    "assert(accuracy is not None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-6ff9da944b3b7772",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Bonus\n",
    "\n",
    "- Visualize the samples where the model is very wrong\n",
    "- Conclusion\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-15ef6db03f1c2b3d",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "# error test\n",
    "## BEGIN SOLUTION\n",
    "print(\"Erreur:\\n\",y_test==y_pred)\n",
    "## END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-97c8f254e9286ad5",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## Optional (test with a random forest model, SVM)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-e033ecfdc568a51b",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Test using a Random Forest model\n",
    "\n",
    "**To do:** modify the parameters of RandomForestClassifier to improve the score.\n",
    "\n",
    "It is possible to achieve at least 97% by simply adjusting the values of n_estimators and max_features. The documentation is available at this address:\n",
    "\n",
    " - http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html\n",
    "\n",
    "**to do** in the two following cells\n",
    "\n",
    "1. Learning of the model with display of the score\n",
    "2. Model testing and analysis of the prediction quality(criteria: accuracy_score, r2_score)\n",
    "  - calculation of y_pred and accuracy  (prediction rate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-45d74d56d81a091b",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "model=None\n",
    "### BEGIN SOLUTION\n",
    "model = RandomForestClassifier(n_estimators=7,verbose=1,max_features=10)\n",
    "model = model.fit(X_train,y_train) \n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-1daf84f25e32c09b",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(model.score(X_train,y_train))\n",
    "print(\"score=\",model.score(X_train,y_train))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-c880adba555f8033",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "y_pred = None\n",
    "accuracy = None\n",
    "### BEGIN SOLUTION\n",
    "y_pred=model.predict(X_test)\n",
    "print(\"predictions:\\n\",y_pred)\n",
    "accuracy=accuracy_score(y_pred,y_test)\n",
    "print(\"taux de prediction {:3d}%\".format(int(accuracy*100)))\n",
    "print(\"R2 score  {:.2f}\".format(r2_score(y_test, y_pred)))\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-441141c957d59d42",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(len(y_test) == len(y_pred))\n",
    "assert(accuracy is not None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-d04ab01fee510744",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Test using a Support Vector Machine model (SVM)\n",
    "\n",
    "**To do:** modify the parameters of svm.SVC to improve the score. It is possible to achieve at least 95%.\n",
    "\n",
    "The documentation is available at this address:\n",
    "\n",
    "- http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html\n",
    "\n",
    "**to do** in the two following cells\n",
    "\n",
    "1. Learning of the model with display of the score\n",
    "2. Model testing and analysis of the prediction quality(criteria: accuracy_score, r2_score)\n",
    "  - calculation of y_pred and accuracy  (prediction rate)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-1af0d6c56eb48295",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "from sklearn import svm\n",
    "\n",
    "model=None\n",
    "### BEGIN SOLUTION\n",
    "model = svm.SVC(C=1.0, kernel=\"rbf\", degree=3)\n",
    "model = model.fit(X_train,y_train)\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-9fec12d1f86a7cf4",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(model.score(X_train,y_train))\n",
    "print(\"score=\",model.score(X_train,y_train))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-8c4382a1727db67b",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "y_pred == None\n",
    "accuracy = None\n",
    "### BEGIN SOLUTION\n",
    "y_pred=model.predict(X_test)\n",
    "print(\"predictions:\\n\",y_pred)\n",
    "accuracy=accuracy_score(y_pred,y_test)\n",
    "print(\"taux de prediction {:3d}%\".format(int(accuracy*100)))\n",
    "print(\"R2 score  {:.2f}\".format(r2_score(y_test, y_pred)))\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-b06cbd2cf72ba4c5",
     "locked": true,
     "points": 3,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "assert(len(y_test) == len(y_pred))\n",
    "assert(accuracy is not None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-d7fe209bfd3b6f65",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "### Analysis and conclusion\n",
    "\n",
    "In the following cell, write your analysis and conclusion using Markdown syntax.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "cell-52a120130633e290",
     "locked": false,
     "points": 10,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "source": [
    "%% BEGIN SOLUTION\n",
    "\n",
    "On constate que dans ce cas l'algorithme SVM donne le meilleur résultat avec un taux de prédiction de 99%\n",
    "\n",
    "%% END SOLUTION\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "cell-26ac1b0be7fb8070",
     "locked": true,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "## This is the End"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Create Assignment",
  "hide_input": false,
  "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.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table des matières",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
