{ "cells": [ { "cell_type": "markdown", "id": "3768ec43", "metadata": {}, "source": [ "# Intel® Extension for Scikit-learn Linear 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 os\n", "import requests\n", "import warnings\n", "from IPython.display import HTML\n", "\n", "warnings.filterwarnings(\"ignore\")" ] }, { "cell_type": "markdown", "id": "ad7ce109", "metadata": {}, "source": [ "### Download the data" ] }, { "cell_type": "code", "execution_count": 2, "id": "801ea6cd", "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": "03431aec", "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", "\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/uxlfoundation/scikit-learn-intelex)\n" ] } ], "source": [ "from sklearnex import patch_sklearn\n", "\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://uxlfoundation.github.io/scikit-learn-intelex/latest/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/uxlfoundation/scikit-learn-intelex/issues)." ] }, { "cell_type": "markdown", "id": "f80273e7", "metadata": {}, "source": [ "Training of the Linear Regression 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.03 s'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sklearn.linear_model import LinearRegression\n", "\n", "params = {\"n_jobs\": -1, \"copy_X\": False}\n", "start = timer()\n", "model = LinearRegression(**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 Linear Regression 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.7716818451881409'" ] }, "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 LinearRegression" ] }, { "cell_type": "code", "execution_count": 9, "id": "6f64ba97", "metadata": {}, "outputs": [], "source": [ "from sklearnex import unpatch_sklearn\n", "\n", "unpatch_sklearn()" ] }, { "cell_type": "markdown", "id": "f242c6da", "metadata": {}, "source": [ "Training of the Linear Regression 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.53 s'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sklearn.linear_model import LinearRegression\n", "\n", "start = timer()\n", "model = LinearRegression(**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 Linear Regression algorithm with original Scikit-learn" ] }, { "cell_type": "code", "execution_count": 11, "id": "cd9e726c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Original Scikit-learn MSE: 0.7716856598854065'" ] }, "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": "91fb14e4", "metadata": {}, "outputs": [ { "data": { "text/html": [ "

Compare MSE metric of patched Scikit-learn and original

MSE metric of patched Scikit-learn: 0.7716818451881409
MSE metric of unpatched Scikit-learn: 0.7716856598854065
Metrics ratio: 0.9999950528144836

With Scikit-learn-intelex patching you can:

" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "HTML(\n", " f\"

Compare MSE metric of patched Scikit-learn and original

\"\n", " f\"MSE metric of patched Scikit-learn: {mse_metric_opt}
\"\n", " f\"MSE metric of unpatched Scikit-learn: {mse_metric_original}
\"\n", " f\"Metrics ratio: {mse_metric_opt/mse_metric_original}
\"\n", " f\"

With Scikit-learn-intelex patching you can:

\"\n", " f\"\"\n", ")" ] } ], "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 }