{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3768ec43",
   "metadata": {},
   "source": [
    "# Intel® Extension for Scikit-learn Lasso Regression for YearPredictionMSD dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b1b922d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from timeit import default_timer as timer\n",
    "from sklearn import metrics\n",
    "from sklearn.model_selection import train_test_split\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import requests\n",
    "import warnings\n",
    "import os\n",
    "from IPython.display import HTML\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db2d1c39",
   "metadata": {},
   "source": [
    "### Download the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e58a6e28",
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_dir = 'data'\n",
    "dataset_name = 'year_prediction_msd'\n",
    "url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00203/YearPredictionMSD.txt.zip'\n",
    "\n",
    "os.makedirs(dataset_dir, exist_ok=True)\n",
    "local_url = os.path.join(dataset_dir, os.path.basename(url))\n",
    "\n",
    "if not os.path.isfile(local_url):\n",
    "    response = requests.get(url, stream=True)\n",
    "    with open(local_url, 'wb+') as file:\n",
    "        for data in response.iter_content(8192):\n",
    "            file.write(data)\n",
    "    \n",
    "year = pd.read_csv(local_url, header=None)\n",
    "x = year.iloc[:, 1:].to_numpy(dtype=np.float32)\n",
    "y = year.iloc[:, 0].to_numpy(dtype=np.float32)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "532874ab",
   "metadata": {},
   "source": [
    "Split the data into train and test sets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0d332789",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((463810, 90), (51535, 90), (463810,), (51535,))"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=0)\n",
    "x_train.shape, x_test.shape, y_train.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "246f819f",
   "metadata": {},
   "source": [
    "### Normalize the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "454a341c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n",
    "scaler_x = MinMaxScaler()\n",
    "scaler_y = StandardScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "df400504",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler_x.fit(x_train)\n",
    "x_train = scaler_x.transform(x_train)\n",
    "x_test = scaler_x.transform(x_test)\n",
    "\n",
    "scaler_y.fit(y_train.reshape(-1, 1))\n",
    "y_train = scaler_y.transform(y_train.reshape(-1, 1)).ravel()\n",
    "y_test = scaler_y.transform(y_test.reshape(-1, 1)).ravel()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe1d4fac",
   "metadata": {},
   "source": [
    "### Patch original Scikit-learn with Intel® Extension for Scikit-learn\n",
    "Intel® Extension for Scikit-learn (previously known as daal4py) contains drop-in replacement functionality for the stock Scikit-learn package. You can take advantage of the performance optimizations of Intel® Extension for Scikit-learn by adding just two lines of code before the usual Scikit-learn imports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ef6938df",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Intel(R) Extension for Scikit-learn* enabled (https://github.com/intel/scikit-learn-intelex)\n"
     ]
    }
   ],
   "source": [
    "from sklearnex import patch_sklearn\n",
    "patch_sklearn()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20c5ab48",
   "metadata": {},
   "source": [
    "Intel® Extension for Scikit-learn patching affects performance of specific Scikit-learn functionality. Refer to the [list of supported algorithms and parameters](https://intel.github.io/scikit-learn-intelex/algorithms.html) for details. In cases when unsupported parameters are used, the package fallbacks into original Scikit-learn. If the patching does not cover your scenarios, [submit an issue on GitHub](https://github.com/intel/scikit-learn-intelex/issues)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f80273e7",
   "metadata": {},
   "source": [
    "Training of the Lasso algorithm with Intel® Extension for Scikit-learn for YearPredictionMSD dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a4dd1c7e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Intel® extension for Scikit-learn time: 0.06 s'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "params = {\n",
    "    \"alpha\": 0.01,    \n",
    "    \"fit_intercept\": False,\n",
    "    \"random_state\": 0,\n",
    "    \"copy_X\": False,\n",
    "}\n",
    "start = timer()\n",
    "model = Lasso(**params).fit(x_train, y_train)\n",
    "train_patched = timer() - start\n",
    "f\"Intel® extension for Scikit-learn time: {train_patched:.2f} s\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f10b51fc",
   "metadata": {},
   "source": [
    "Predict and get a result of the Lasso algorithm with Intel® Extension for Scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d4295a26",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Patched Scikit-learn MSE: 0.9676607251167297'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_predict = model.predict(x_test)\n",
    "mse_metric_opt = metrics.mean_squared_error(y_test, y_predict)\n",
    "f'Patched Scikit-learn MSE: {mse_metric_opt}'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbe6db0d",
   "metadata": {},
   "source": [
    "### Train the same algorithm with original Scikit-learn\n",
    "In order to cancel optimizations, we use *unpatch_sklearn* and reimport the class Lasso"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6f64ba97",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearnex import unpatch_sklearn\n",
    "unpatch_sklearn()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f242c6da",
   "metadata": {},
   "source": [
    "Training of the Lasso algorithm with original Scikit-learn library for YearPredictionMSD dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "67243849",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Original Scikit-learn time: 0.83 s'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "start = timer()\n",
    "model = Lasso(**params).fit(x_train, y_train)\n",
    "train_unpatched = timer() - start\n",
    "f\"Original Scikit-learn time: {train_unpatched:.2f} s\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c85a125c",
   "metadata": {},
   "source": [
    "Predict and get a result of the Lasso algorithm with original Scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cd9e726c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Original Scikit-learn MSE: 0.9676599502563477'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_predict = model.predict(x_test)\n",
    "mse_metric_original = metrics.mean_squared_error(y_test, y_predict)\n",
    "f'Original Scikit-learn MSE: {mse_metric_original}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "13c86289",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<h3>Compare MSE metric of patched Scikit-learn and original</h3>MSE metric of patched Scikit-learn: 0.9676607251167297 <br>MSE metric of unpatched Scikit-learn: 0.9676599502563477 <br>Metrics ratio: 1.0000008344650269 <br><h3>With Scikit-learn-intelex patching you can:</h3><ul><li>Use your Scikit-learn code for training and prediction with minimal changes (a couple of lines of code);</li><li>Fast execution training and prediction of Scikit-learn models;</li><li>Get the similar quality</li><li>Get speedup in <strong>13.7</strong> times.</li></ul>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "HTML(f\"<h3>Compare MSE metric of patched Scikit-learn and original</h3>\"\n",
    "     f\"MSE metric of patched Scikit-learn: {mse_metric_opt} <br>\"\n",
    "     f\"MSE metric of unpatched Scikit-learn: {mse_metric_original} <br>\"\n",
    "     f\"Metrics ratio: {mse_metric_opt/mse_metric_original} <br>\"\n",
    "     f\"<h3>With Scikit-learn-intelex patching you can:</h3>\"\n",
    "     f\"<ul>\"\n",
    "     f\"<li>Use your Scikit-learn code for training and prediction with minimal changes (a couple of lines of code);</li>\"\n",
    "     f\"<li>Fast execution training and prediction of Scikit-learn models;</li>\"\n",
    "     f\"<li>Get the similar quality</li>\"\n",
    "     f\"<li>Get speedup in <strong>{(train_unpatched/train_patched):.1f}</strong> times.</li>\"\n",
    "     f\"</ul>\")"
   ]
  }
 ],
 "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.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
