{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "30b61190-61c1-4dd2-a9ec-acbadc8a52ef",
   "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",
    "\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": "code",
   "execution_count": null,
   "id": "a70c5553-ad01-4d43-93fb-50c085f09a64",
   "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",
    "\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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55af6bf5-2399-4427-9260-3b51770c1744",
   "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": "code",
   "execution_count": null,
   "id": "2de452bf-94f8-4d77-837d-2f4af910b133",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_results(y_test, y_pred):\n",
    "    df_res = pd.DataFrame({'y_test': y_test, 'y_pred': y_pred})\n",
    "    df_res_s = df_res.stack().reset_index(name='value').rename({'level_0': 'idx', 'level_1': 'variable'}, axis=1)\n",
    "    return sns.lineplot(data = df_res_s, x='idx', y='value', hue='variable')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfc86712-43ad-431c-ace2-7297261f7624",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "https://www.kaggle.com/hmavrodiev/london-bike-sharing-dataset\n",
    "\n",
    "### Metadata:\n",
    "- \"timestamp\" - timestamp field for grouping the data\n",
    "- \"cnt\" - the count of a new bike shares\n",
    "- \"t1\" - real temperature in C\n",
    "- \"t2\" - temperature in C \"feels like\"\n",
    "- \"hum\" - humidity in percentage\n",
    "- \"windspeed\" - wind speed in km/h\n",
    "- \"weathercode\" - category of the weather\n",
    "- \"isholiday\" - boolean field - 1 holiday / 0 non holiday\n",
    "- \"isweekend\" - boolean field - 1 if the day is weekend\n",
    "- \"season\" - category field meteorological seasons: 0-spring ; 1-summer; 2-fall; 3-winter.\n",
    "\n",
    "- \"weathe_code\" category description:\n",
    "    - 1 = Clear ; mostly clear but have some values with haze/fog/patches of fog/ fog in vicinity \n",
    "    - 2 = scattered clouds / few clouds \n",
    "    - 3 = Broken clouds \n",
    "    - 4 = Cloudy \n",
    "    - 7 = Rain/ light Rain shower/ Light rain \n",
    "    - 10 = rain with thunderstorm \n",
    "    - 26 = snowfall \n",
    "    - 94 = Freezing Fog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d395b133-9643-4ccf-b8d7-76f722a6d4b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('bike_london.csv')\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2594e91f-23a4-4b0c-a379-6ecb0d838f18",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "174131dc-0d23-4491-83fd-d807935dc5a6",
   "metadata": {},
   "source": [
    "## Change type of *timestamp* to datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c848c7b3-f10c-4337-9cb0-70d43accf0e7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c053aa-2051-4696-8982-da3fabf1ce33",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c61ce0f0-9204-4048-ac5a-9cdfa6e19346",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "318b58f1-af44-46de-8aee-cd3e10b63839",
   "metadata": {},
   "source": [
    "## Create new time related features out of the timestamp\n",
    "- day, month, year, hour"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8270d847-23f1-4507-8cfb-36afdc24bce4",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcaef87f-342b-4b15-9395-d46535912497",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "c449b38a-6e0d-4593-90ca-980125fd8881",
   "metadata": {},
   "source": [
    "## How many values are in the individual years?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2c9da64-1649-463b-8a51-7ae3130a1e91",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "611134f9-b05f-46b7-ac34-7f46c3869010",
   "metadata": {},
   "source": [
    "## *cnt* is the target variable in our case, let's take a look at the values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c808b80-f6e6-47da-80d6-e4d8aaad3f78",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.lineplot(data=df, x=df.timestamp, y='cnt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1777ee9a-5999-4092-895a-6170a5de0f9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.boxplot(data=df, y='cnt')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "096bc9dc-2344-4eae-b5fc-a5f237562f3f",
   "metadata": {},
   "source": [
    "## Split the data into the X and y part"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62084c12-6129-4a75-937c-c94b7950ccff",
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = df.loc[:, (df.columns != 'cnt') & (df.columns != 'timestamp')], df.loc[:, 'cnt']\n",
    "X.shape, y.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c284e871-61bb-4176-b98a-10e1c33b4f52",
   "metadata": {},
   "source": [
    "## We will use first 14000 instances as the training set\n",
    "- Beware that data are time-related so it is certainly not a great idea to split the data randomly\n",
    "- Do you know why we shouldn't split the data randomly?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8509e641-d50a-478f-a4bd-35149e784265",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test = X.iloc[:14000, :], X.iloc[14000:, :]\n",
    "y_train, y_test = y.iloc[:14000], y.iloc[14000:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04de8bdf-ae09-4615-a40f-063752b80a80",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "c861b822-1e0a-49ed-9a16-382c5bb54d58",
   "metadata": {},
   "source": [
    "## Vizualize results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3477f977-368c-4653-b912-a37f365ea397",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "0a47c419-0b9a-4c4c-bf80-cfdb37ff200d",
   "metadata": {},
   "source": [
    "## Let's take a look at the coefficient values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2c55ca3-e441-485f-b976-6af12676723f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f99ffd9-21a8-4509-ad50-ec87583beb2d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "a00c0a52-f249-4dea-a6d8-9555bd3c302d",
   "metadata": {},
   "source": [
    "## Try to apply the [MinMax](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) scaling to the features and repeat the model fitting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afa05d48-c592-47f0-97ee-8146f299b5c7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23d26b31-6234-44ef-a2f7-4d9bc27025c5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "b8251b53-b2c6-4227-9d83-1f1c87285089",
   "metadata": {},
   "source": [
    "## Did the coefficient values change?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7d434ad-e4fb-4cdd-b29c-c3bb3082970f",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88b3c4c4-0d41-46a6-bdab-31f6569608f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "edf7264e-1c7b-41f2-9680-41295d0f5786",
   "metadata": {},
   "source": [
    "## Try to apply the [StandardScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler) to the features and repeat the model fitting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8479560-b08c-49f7-bc4c-33dce0b31ef9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "774bbef2-09cb-4044-a641-611da3d94055",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "a856188f-41b7-4e5d-8693-81b78dd0f921",
   "metadata": {},
   "source": [
    "## Did the coefficient values change?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4aa6b6b-0f49-4129-acde-724de3bfc975",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72ac44c3-dad4-48d4-b19c-0d415e2c021c",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ba2bb59-39f5-4e69-b2dc-b6ff7f85eb37",
   "metadata": {},
   "source": [
    "## Ordinary least squares Linear Regression is the simplest model but there are several other ones which allow us to regularize the coefficient values\n",
    "- We will start with Lasso (L1) regression and continue with Ridge (L2) regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7240825f-3637-4997-8a88-80ec1d5ea237",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "fcb0c1b5-3307-402b-bbda-0d1a745061c8",
   "metadata": {},
   "source": [
    "## Did the coefficient values change?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18094c09-2f5f-4c84-b9ec-2eaf46fcb361",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e32e607-e283-4a3e-ba3c-f3f4d04213aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc595aaf-f44f-4844-9a63-b108c7a36552",
   "metadata": {},
   "source": [
    "### Warning: Alpha values are usually set to values between 0 and 1, so we present more extreme cases just for demonstration, \n",
    "This is kind of \"don't try this at home\" section :-)\n",
    "- Regularization adds a little bit of bias to the model thus the variance (and overfitting) are reduced\n",
    "- It also helps with co-linearity issues and error amplification in such case\n",
    "- Lasso regression can help you even with feature selection because it creates a sparse weight vector (some weight are set to 0 if the alpha values is high enough)\n",
    "\n",
    "### The main point is that regularization adds penalization for a high weight values thus the models is not dependant solely on a single (or couple) of features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6164f843-d313-466c-92dd-44231043f6e7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51acb720-1dd2-45c2-a4db-855f64800b8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "985197a2-3a16-419f-8d63-41a54e19ce13",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c107d91-3850-476f-a099-65a5976e5783",
   "metadata": {},
   "source": [
    "## Let's try scaling and regularization together"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e49417f4-a8b0-45dc-bc43-dee80283dd5c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "786fed81-335a-4604-b263-3f03c9a41d9c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82e9fb23-841f-436f-9f67-05cabe482a49",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad2efd62-5d18-4a1e-af08-db1eb7f61d8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eec8b8e1-6366-4eb2-9688-d43b2efb09b5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86c7bd57-395b-4104-b8b8-177752725905",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c28b969-b1bf-400a-a973-96787a54ab34",
   "metadata": {},
   "outputs": [],
   "source": [
    "reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6223ede-f621-4e6e-bc9b-7d6a7e3258d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75de85a9-56c2-4f70-9fa8-7769c505e96a",
   "metadata": {},
   "source": [
    "## Try different alpha values for the Ridge regression as well"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "285f186e-c19c-4dc5-830e-0e53867cc15c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68735488-57f4-4df4-851a-33c44e7eca39",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d96c322a-2013-4407-a434-b10aeceb6de0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6317e057-3cb8-49b0-bfe0-c12685207aa0",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ca30d36-6b4c-4b5d-bea0-0e71e367845f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce59d8a5-3b49-4a81-85e1-ef6c7dfbb87a",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba7f3243-0a68-4d9d-a6b4-52f9c39953d2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77e34934-929c-4e9c-8404-61f9341b9b41",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(16, 9))\n",
    "sns.barplot(x=X_train.columns, y=reg.coef_)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cf14aab-4647-49b7-bc66-524dd7476346",
   "metadata": {},
   "source": [
    "## Take a look at the Bias-Variance trade-off on this web site:\n",
    "\n",
    "https://mlu-explain.github.io/bias-variance/"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3782fb16-bb52-461c-a415-5f13f22aa1f0",
   "metadata": {},
   "source": [
    "# Task (2p)\n",
    "- Use the ElasticNet model (https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html#sklearn.linear_model.ElasticNet)\n",
    "- Use MinMax, Standard and Power Transform preprocessing together with the ElasticNet model\n",
    "- Tune the *alpha* and *l1_ratio* hyper parameters\n",
    "- Which setup works best out of the ones you tried?\n",
    "\n",
    "**Write down conclusion to the Markdown cell**"
   ]
  }
 ],
 "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
}
