{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/asus/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n",
      "  \"This module will be removed in 0.20.\", DeprecationWarning)\n"
     ]
    }
   ],
   "source": [
    "from PIL import Image, ImageOps\n",
    "import numpy, os\n",
    "from sklearn.cross_validation import cross_val_score\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "path=\"dataset/\"\n",
    "Xlist=[]\n",
    "Ylist=[]\n",
    "size = 100, 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "reading dataset images files\n"
     ]
    }
   ],
   "source": [
    "print(\"reading dataset images files\")\n",
    "for directory in os.listdir(path):\n",
    "    for file in os.listdir(path+directory):\n",
    "        #print(path+directory+\"/\"+file)\n",
    "        img=Image.open(path+directory+\"/\"+file)\n",
    "        #resize\n",
    "        thumb = ImageOps.fit(img, size, Image.ANTIALIAS)\n",
    "        image_data = np.array(thumb).flatten()[:100]\n",
    "        #image_data=numpy.array(img).flatten()[:50] #in my case the images dont have the same dimensions, so [:50] only takes the first 50 values\n",
    "        Xlist.append(image_data)\n",
    "        Ylist.append(directory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(Xlist, Ylist, test_size=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### AdaBoostClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.762399355878\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import AdaBoostClassifier\n",
    "clf=AdaBoostClassifier(n_estimators=100)\n",
    "scores = cross_val_score(clf, X_train, y_train, cv=3)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GaussianNB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.721908939014\n"
     ]
    }
   ],
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "clf = GaussianNB()\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### KNeighborsClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.751357560568\n"
     ]
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "clf = KNeighborsClassifier(n_neighbors=10)\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### LinearSVC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.66238512949\n"
     ]
    }
   ],
   "source": [
    "from sklearn.svm import LinearSVC\n",
    "clf = LinearSVC()\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SVC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.668650793651\n"
     ]
    }
   ],
   "source": [
    "from sklearn.svm import SVC\n",
    "clf = SVC()\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GaussianProcessClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.491228070175\n"
     ]
    }
   ],
   "source": [
    "from sklearn.gaussian_process import GaussianProcessClassifier\n",
    "clf = GaussianProcessClassifier()\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### RandomForestClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.775793650794\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "clf = RandomForestClassifier()\n",
    "scores = cross_val_score(clf, Xlist, Ylist)\n",
    "print(scores.mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hyperparameters Tuning using sklearn pipeline and gridsearch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "from sklearn.model_selection import RandomizedSearchCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "pipe = [Pipeline([\n",
    "        ('clf', RandomForestClassifier()),\n",
    "    ]),\n",
    "    Pipeline([\n",
    "        ('clf', KNeighborsClassifier()),\n",
    "    ]),\n",
    "    Pipeline([\n",
    "        ('clf', GaussianProcessClassifier()),\n",
    "    ]),\n",
    "    Pipeline([\n",
    "        ('clf', AdaBoostClassifier()),\n",
    "    ]),\n",
    "    Pipeline([\n",
    "        ('clf', SVC()),\n",
    "    ]),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "param_grid = [dict(clf__n_estimators=[3, 10, 100]),\n",
    "              dict(clf__n_neighbors=[3,10]),\n",
    "              dict(clf__n_restarts_optimizer=[0,1]),\n",
    "              dict(clf__n_estimators=[3, 10, 100]),\n",
    "              dict(clf__C=[3, 10, 100]),\n",
    "             ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "grid_search = GridSearchCV(pipe, param_grid=param_grid, n_jobs=-1, verbose=1, cv=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Utility function to report best scores\n",
    "def report(results, n_top=10):\n",
    "    for i in range(1, n_top + 1):\n",
    "        candidates = np.flatnonzero(results['rank_test_score'] == i)\n",
    "        for candidate in candidates:\n",
    "            print(\"Model with rank: {0}\".format(i))\n",
    "            print(\"Mean validation score: {0:.3f} (std: {1:.3f})\".format(\n",
    "                  results['mean_test_score'][candidate],\n",
    "                  results['std_test_score'][candidate]))\n",
    "            print(\"Parameters: {0}\".format(results['params'][candidate]))\n",
    "            print(\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----\n",
      "classifier:\n",
      "RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n",
      "            max_depth=None, max_features='auto', max_leaf_nodes=None,\n",
      "            min_impurity_decrease=0.0, min_impurity_split=None,\n",
      "            min_samples_leaf=1, min_samples_split=2,\n",
      "            min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,\n",
      "            oob_score=False, random_state=None, verbose=0,\n",
      "            warm_start=False)\n",
      "Fitting 3 folds for each of 3 candidates, totalling 9 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=-1)]: Done   9 out of   9 | elapsed:    0.8s finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GridSearchCV took 1.45 seconds for 3 candidate parameter settings.\n",
      "finished GridSearch\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.800 (std: 0.085)\n",
      "Parameters: {'clf__n_estimators': 100}\n",
      "\n",
      "Model with rank: 2\n",
      "Mean validation score: 0.778 (std: 0.035)\n",
      "Parameters: {'clf__n_estimators': 3}\n",
      "\n",
      "Model with rank: 3\n",
      "Mean validation score: 0.741 (std: 0.046)\n",
      "Parameters: {'clf__n_estimators': 10}\n",
      "\n",
      "-----\n",
      "classifier:\n",
      "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
      "           metric_params=None, n_jobs=1, n_neighbors=5, p=2,\n",
      "           weights='uniform')\n",
      "Fitting 3 folds for each of 2 candidates, totalling 6 fits\n",
      "GridSearchCV took 0.35 seconds for 2 candidate parameter settings.\n",
      "finished GridSearch\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.756 (std: 0.056)\n",
      "Parameters: {'clf__n_neighbors': 10}\n",
      "\n",
      "Model with rank: 2\n",
      "Mean validation score: 0.748 (std: 0.111)\n",
      "Parameters: {'clf__n_neighbors': 3}\n",
      "\n",
      "-----\n",
      "classifier:\n",
      "GaussianProcessClassifier(copy_X_train=True, kernel=None,\n",
      "             max_iter_predict=100, multi_class='one_vs_rest', n_jobs=1,\n",
      "             n_restarts_optimizer=0, optimizer='fmin_l_bfgs_b',\n",
      "             random_state=None, warm_start=False)\n",
      "Fitting 3 folds for each of 2 candidates, totalling 6 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=-1)]: Done   6 out of   6 | elapsed:    0.1s remaining:    0.0s\n",
      "[Parallel(n_jobs=-1)]: Done   6 out of   6 | elapsed:    0.1s finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GridSearchCV took 0.47 seconds for 2 candidate parameter settings.\n",
      "finished GridSearch\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.496 (std: 0.005)\n",
      "Parameters: {'clf__n_restarts_optimizer': 0}\n",
      "\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.496 (std: 0.005)\n",
      "Parameters: {'clf__n_restarts_optimizer': 1}\n",
      "\n",
      "-----\n",
      "classifier:\n",
      "AdaBoostClassifier(algorithm='SAMME.R', base_estimator=None,\n",
      "          learning_rate=1.0, n_estimators=50, random_state=None)\n",
      "Fitting 3 folds for each of 3 candidates, totalling 9 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=-1)]: Done   6 out of   6 | elapsed:    0.3s remaining:    0.0s\n",
      "[Parallel(n_jobs=-1)]: Done   6 out of   6 | elapsed:    0.3s finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GridSearchCV took 1.06 seconds for 3 candidate parameter settings.\n",
      "finished GridSearch\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.793 (std: 0.088)\n",
      "Parameters: {'clf__n_estimators': 3}\n",
      "\n",
      "Model with rank: 2\n",
      "Mean validation score: 0.785 (std: 0.084)\n",
      "Parameters: {'clf__n_estimators': 10}\n",
      "\n",
      "Model with rank: 3\n",
      "Mean validation score: 0.763 (std: 0.048)\n",
      "Parameters: {'clf__n_estimators': 100}\n",
      "\n",
      "-----\n",
      "classifier:\n",
      "SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n",
      "  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',\n",
      "  max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
      "  tol=0.001, verbose=False)\n",
      "Fitting 3 folds for each of 3 candidates, totalling 9 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=-1)]: Done   9 out of   9 | elapsed:    0.9s finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GridSearchCV took 0.36 seconds for 3 candidate parameter settings.\n",
      "finished GridSearch\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.689 (std: 0.067)\n",
      "Parameters: {'clf__C': 3}\n",
      "\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.689 (std: 0.067)\n",
      "Parameters: {'clf__C': 10}\n",
      "\n",
      "Model with rank: 1\n",
      "Mean validation score: 0.689 (std: 0.067)\n",
      "Parameters: {'clf__C': 100}\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=-1)]: Done   9 out of   9 | elapsed:    0.1s finished\n"
     ]
    }
   ],
   "source": [
    "from time import time\n",
    "\n",
    "for i in range(len(pipe)):\n",
    "        start = time()\n",
    "        print(\"-----\")\n",
    "        print(\"classifier:\")\n",
    "        print(pipe[i].named_steps['clf'])\n",
    "        grid_search = GridSearchCV(pipe[i], param_grid[i], n_jobs=-1, verbose=1, cv=3)\n",
    "        grid_search.fit(X_train, y_train)\n",
    "        print(\"GridSearchCV took %.2f seconds for %d candidate parameter settings.\"\n",
    "              % (time() - start, len(grid_search.cv_results_['params'])))\n",
    "        print(\"finished GridSearch\")\n",
    "        report(grid_search.cv_results_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
