{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b89dc436-dd76-4d51-b5ee-ca8304f436cd",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Supervised learning - Regression\n",
    "Goal of the excercise is to learn how to use Scikit-learn library for a regression tasks employing various linear regression models and moreover evaluate the performance of the proposed models.\n",
    "\n",
    "## Models\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html#sklearn.linear_model.Lasso\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html#sklearn.linear_model.ElasticNet\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html\n",
    "\n",
    "## Preprocessing methods\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler\n",
    "- https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PowerTransformer.html#sklearn.preprocessing.PowerTransformer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87ed6f25-ec81-48b2-9bde-d20a4f7ab900",
   "metadata": {},
   "source": [
    "![ml_meme.jpeg](https://homel.vsb.cz/~svo0175/ml_meme.jpeg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43b18a1f-3ffe-4831-a2cf-59067d8c63a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "import math\n",
    "\n",
    "from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
    "from sklearn.preprocessing import MinMaxScaler, StandardScaler, PowerTransformer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "741b0897-c4b4-4d76-93b6-3a4d2ab49655",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Computes MAPE\n",
    "\"\"\"\n",
    "def mean_absolute_percentage_error(y_true: np.array, y_pred: np.array) -> float:\n",
    "    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n",
    "\n",
    "def compute_metrics(df: pd.DataFrame) -> pd.DataFrame:\n",
    "    y_true, y_pred = df['y_true'].values, df['y_pred'].values\n",
    "    return compute_metrics_raw(y_true, y_pred)\n",
    "\n",
    "def compute_metrics_raw(y_true: pd.Series, y_pred: pd.Series) -> pd.DataFrame:\n",
    "    mae, mse, rmse, mape = mean_absolute_error(y_true=y_true, y_pred=y_pred), mean_squared_error(y_true=y_true, y_pred=y_pred), np.sqrt(mean_squared_error(y_true=y_true, y_pred=y_pred)), mean_absolute_percentage_error(y_true=y_true, y_pred=y_pred)\n",
    "    return pd.DataFrame.from_records([{'MAE': mae, 'MSE': mse, 'RMSE': rmse, 'MAPE': mape}], index=[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14afa8d4-8af8-4770-b5c8-0d4d523c06cb",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Dataset\n",
    "https://www.kaggle.com/datasets/harinir/petrol-consumption\n",
    "\n",
    "## Task\n",
    "Build a regression model for prediction of petrol consumption in the 48 USA states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12fd1a57-7307-464e-aeb5-0a7177a2a0ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('petrol_consumption.csv')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a084465-8fb8-4c38-8f81-6884ba1e6517",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "242f1dd9-b6ba-402d-89a4-a63107f7d2e8",
   "metadata": {},
   "source": [
    "## Do we have any missing data?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b1be4a5-1cef-4726-b781-ddcfa0e85f36",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.isna().sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30ac8eaf-3847-4bb2-a878-94fe14663ba5",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Let's take a look at the dataset\n",
    "- Can you see some relationships among the features from the pairplot?\n",
    "- Do you think that the features are normally distributed?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4653768-8777-4299-9148-e45905e084b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(12, 12))\n",
    "sns.pairplot(df)\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2329397d-a60e-40bf-af5c-365021e4af3f",
   "metadata": {
    "tags": []
   },
   "source": [
    "![meme_regression.png](https://homel.vsb.cz/~svo0175/meme_regression.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4098290-1d55-41d6-a398-93cd824219df",
   "metadata": {},
   "source": [
    "## What about the a correlation coeffs'?\n",
    "- What row/column is the most important from the heatmap? Why?\n",
    "- Are correlations among predictors good or bad?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e163eda5-a616-489a-857a-b981c6d40c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 9))\n",
    "sns.heatmap(df.corr(), square=True, cmap='RdYlGn', vmin=-1, vmax=1, annot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c52a6be-25d5-4ca8-ad3d-eef58e9389d6",
   "metadata": {},
   "source": [
    "## Can you see any outliers in the data?\n",
    "## What about skewness or variance differences?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0262817-a90f-437b-a570-5f80ab68d72e",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, df.shape[1], figsize=(10, 5))\n",
    "\n",
    "for i, col in enumerate(df.columns):\n",
    "    ax = axes.flatten()[i]\n",
    "    sns.boxplot(data=df, y=col, ax=ax)\n",
    "        \n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9b90b9a-5832-4dbf-a97a-ae6d78387fd7",
   "metadata": {},
   "source": [
    "## Let's build our first simple regression models with just 2 variables and compare them\n",
    "- We will split the data into train/test set\n",
    "- Then we can build the models and evaluate them\n",
    "\n",
    "### There are many metrics used for the perormance evaluation\n",
    "- MAE, RMSE, MAPE, R2, etc. - do you know what these abbr. mean?\n",
    "- Do we want these metrics to go lower or higher?\n",
    "- You can take a look at [this](https://towardsdatascience.com/regression-an-explanation-of-regression-metrics-and-what-can-go-wrong-a39a9793d914) or [this](https://www.analyticsvidhya.com/blog/2021/05/know-the-best-evaluation-metrics-for-your-regression-model/) for more details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7255fb43-e02e-4499-be5b-5f43f515b947",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa188905-4ed7-425e-b015-75b66227268e",
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = df.drop('Petrol_Consumption', axis=1), df['Petrol_Consumption']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb129548-75be-4d02-ad38-59506ad361e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "X.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13745c11-4e87-42fb-91fb-f100ec2df2df",
   "metadata": {},
   "outputs": [],
   "source": [
    "y.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "839cc301-cdf9-486c-9944-f19cff481fef",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bb0a950-105e-45d3-89c0-07693629390c",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train.shape, X_test.shape, y_train.shape, y_test.shape "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a65584c-6cde-4ae1-a5d4-94a20bae03bb",
   "metadata": {},
   "source": [
    "### Model 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26c5f9ce-4f31-46cd-af06-25962453b539",
   "metadata": {},
   "outputs": [],
   "source": [
    "s_column = 'Population_Driver_licence(%)'\n",
    "alg = LinearRegression()\n",
    "alg.fit(pd.DataFrame(X_train[s_column]), y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d29c02a5-1e6d-4f20-971c-a4bfadf0ee6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(pd.DataFrame(X_test[s_column]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a70c52f-4456-4379-9ef4-6c773635c570",
   "metadata": {},
   "source": [
    "## How would the regression line formula look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04f0e930-354f-4ae2-9c0f-c34c5a6d29a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.coef_[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e510846-adfd-4d00-a670-997db09e3c0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.intercept_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d1c220b-f907-44d7-bc98-f1fe3aaf8fc5",
   "metadata": {},
   "source": [
    "## Let's take a look at the scatterplot of y_test vs. y_pred\n",
    "- What is the ideal result?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94b8e7db-fb2e-41e1-bb7d-653023d88922",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87fba8e4-97bd-45af-abe6-829651afeef8",
   "metadata": {},
   "source": [
    "## We should always quantify the errors\n",
    "- MAE, RMSE are in the same units as the predicted variable, always take a look at boxplot or basic statistical properties to rationalize the amount of error according to the range or the variable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73301b73-221e-4d33-9823-4cad39479406",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(y=y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a335ec1-fe4a-4126-be64-0b2954ff4b17",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "408feffb-1c31-4dd3-b658-348f090ef7f2",
   "metadata": {},
   "source": [
    "### Model 2\n",
    "- Compare the model with the first one"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60239f55-b304-4fd3-a5ef-08355479caa3",
   "metadata": {},
   "outputs": [],
   "source": [
    "s_column = 'Paved_Highways'\n",
    "alg = LinearRegression()\n",
    "alg.fit(pd.DataFrame(X_train[s_column]), y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77ab4de8-827a-4147-81f8-bbcf6283669b",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(pd.DataFrame(X_test[s_column]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36cf038f-c4e5-4908-9678-cd04f0ebbfe5",
   "metadata": {},
   "source": [
    "## Let's take a look at the scatterplot of y_test vs. y_pred now"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6244c2be-aa53-449f-a800-70cb548b2c8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc2af72f-4908-4799-99ed-2c3d45edff5e",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3574c5e5-fb96-4997-824e-635b4728695f",
   "metadata": {},
   "source": [
    "## Which one of the two models is better and why?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3272aee-0775-4fda-b49a-b308e3497172",
   "metadata": {},
   "source": [
    "## The obvious next step is using more than one feature in the model, so let's try that"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50856347-8795-461a-b9f5-5400fcd85938",
   "metadata": {},
   "source": [
    "### MLR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "396f8bf6-b582-452e-99e0-7049fe391b66",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg = LinearRegression()\n",
    "alg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2edb1f61-5817-42ec-9919-7cf59e8222d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bdd1421-a02f-461a-9193-e7cd6f1d440b",
   "metadata": {},
   "source": [
    "## How would the regression line formula look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68465123-8d35-4e63-b6b1-cf375f66bfe9",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a0bf8ab-c626-469d-b3ba-6f62cd7989c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.intercept_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c13056f1-1aa4-44a6-8ac7-c4151f9291da",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=X_train.columns, y=alg.coef_)\n",
    "plt.xticks(rotation=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f51b262f-75c0-4a40-b368-6dc3b8e1647a",
   "metadata": {},
   "source": [
    "## Let's take a look at the scatterplot of y_test vs. y_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63e26474-22d1-4ec9-a231-34e2f8c24b12",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43255d2d-0eb0-4126-a910-e13a0ae376c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e22a45ef-90fb-460d-874a-d7c41df46a9e",
   "metadata": {},
   "source": [
    "## Is it wise to have a model with coefficients of magnitude higher values than for other variables?\n",
    "- What can go wrong?\n",
    "\n",
    "## What is a colinearity? \n",
    "- Why it may becaome an issue for regression models?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca9de052-1b15-45f4-99e3-ab848c5b3ce5",
   "metadata": {},
   "source": [
    "![colinear_meme.jpg](https://homel.vsb.cz/~svo0175/colinear_meme.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ab4f445-4756-4a92-a654-ea4a2fc0f826",
   "metadata": {},
   "source": [
    "## The method for dealing with both of these issues is called regularization\n",
    "- We have two types of it - L1 (Lasso) and L2 (Ridge). What is the difference between them?\n",
    "- Let's try both of them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a1a0b2e-42b7-44a6-b591-65f18fea2d15",
   "metadata": {},
   "source": [
    "### Lasso"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac70f22e-ff83-4407-a2a1-c77ab5dfd7ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg = Lasso(alpha=3, random_state=13)\n",
    "alg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ef373ba-8d3a-41af-8c73-245f1a0c3374",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cc33ae2-28f3-4fd5-b1de-d419c36e69a8",
   "metadata": {},
   "source": [
    "## How would the regression line formula look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65947baf-1c9a-49ea-8499-892e5587413e",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9af533de-41c2-4479-92c0-ec1f39f48c49",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.intercept_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7d0db72-ec9e-4859-88a1-0c0d3488ea2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=X_train.columns, y=alg.coef_)\n",
    "plt.xticks(rotation=30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "beeae102-6161-47c2-bbc1-45c084355de5",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f05e781c-066a-4950-a793-3dd069ef1c27",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cc3ca35-939a-4e1e-96fd-5401c6ec516e",
   "metadata": {},
   "source": [
    "### Ridge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6f5f556-89d4-47b8-9ba0-002e59c097e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg = Ridge(alpha=1, random_state=13)\n",
    "alg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a639d719-8a98-4627-9fa2-02500d382729",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7634a766-2752-4702-bade-f84043ed547a",
   "metadata": {},
   "source": [
    "## How would the regression line formula look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07099375-8988-45b9-9ccf-db276b81b17f",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab826f8a-086c-407a-b56b-75f5462e3fe0",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.intercept_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "547e17ac-f3c8-490c-857c-a941c0ceafd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=X_train.columns, y=alg.coef_)\n",
    "plt.xticks(rotation=30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e965c2fc-fbfe-4155-b1df-078d0b0de58c",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df83ad69-af94-4d2f-bf0c-4a2264bdbf59",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "622b9b9f-9e4b-4b88-a8ea-00c2d59b5695",
   "metadata": {
    "tags": []
   },
   "source": [
    "## What is the difference among the coefficients values with enabled/disabled regularization?\n",
    "\n",
    "## There are usually differences among the variables ranges which may bring some difficulties for the coefficient optimization. \n",
    "\n",
    "## If the ranges are similar, the optimization process should be a lot easier. \n",
    "\n",
    "## Due to that, we usually use MinMax or StdScale (we are not limited to this two) preprocessing before applying a regression model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65fcb7e0-2e1a-4786-8270-bf0d9a778508",
   "metadata": {},
   "source": [
    "### Why do we fit the scaler only on X_train?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a0e80f2-b299-446e-8cf8-7e2f8fc5c8e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "std_scaler = StandardScaler()\n",
    "std_scaler.fit(X_train)\n",
    "X_train_std = std_scaler.transform(X_train)\n",
    "X_test_std = std_scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7407c6bf-a8c6-4d11-a6b9-0991b19b27bb",
   "metadata": {},
   "source": [
    "### Try 0, 1 and 10 for alpha parameter. What is different?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0de50239-8d16-4fc7-8a52-59c83de32f6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg = Lasso(alpha=1, random_state=13)\n",
    "alg.fit(X_train_std, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4deb171a-589e-4df5-9f1a-0ac7257d0d91",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(X_test_std)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7951b85b-746a-407c-ac94-ccae950e2c7e",
   "metadata": {},
   "source": [
    "## How would the regression line formula look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10bf7405-f799-4b88-b2ba-6e4543860bf9",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b38cdff6-4dce-449c-b216-63e7525d2e85",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg.intercept_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fef5f4e-cb54-4bd1-843f-e3a5ce61d684",
   "metadata": {},
   "source": [
    "## How are now the values different?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fd576bf-4baf-4fa0-a2c7-d7530beb50ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=X_train.columns, y=alg.coef_)\n",
    "plt.xticks(rotation=30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c139573-695c-44b8-a6bd-2434b1db1fdc",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d95e1d8d-96bb-455d-ac60-c04e141c9838",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbcad061-1cbe-45e9-85aa-20d76183e62b",
   "metadata": {},
   "source": [
    "## We are obviously not limited to linear regression for the regression tasks.\n",
    "### Usually there is a regression alternative for most of the classification models in SkLearn. We can try for example tree-based models."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb92c5d3-375a-43d0-8d8f-1628828c2f1b",
   "metadata": {
    "tags": []
   },
   "source": [
    "### Random forest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "215af65c-ade0-46ae-a709-03bc195ebdc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "alg = RandomForestRegressor(n_estimators=5,random_state=13)\n",
    "alg.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5dd16025-c90c-4f2d-b362-243688697328",
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = alg.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02d9d7c8-ecfa-4cef-9ba3-a6ffbc861680",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.barplot(x=alg.feature_importances_, y=X_train.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f10e254e-3895-4086-8a68-2d4aa9cbf4e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(x=y_test, y=y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f634325f-9483-4a4b-b34f-b7286d4dd821",
   "metadata": {},
   "outputs": [],
   "source": [
    "compute_metrics_raw(y_true=y_test, y_pred=y_pred)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91d3988f-02b3-408b-bc33-bc5e09b68109",
   "metadata": {},
   "source": [
    "![all_meme.png](https://homel.vsb.cz/~svo0175/all_meme.png)"
   ]
  }
 ],
 "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.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
