{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4d2a8b6c",
   "metadata": {},
   "source": [
    "#### Database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 247,
   "id": "7be9eeff",
   "metadata": {},
   "outputs": [],
   "source": [
    "PROJECT_PATH = '/home/md/Work/ligalytics/leagues_stable/'\n",
    "import os, sys\n",
    "sys.path.insert(0, PROJECT_PATH)\n",
    "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"leagues.settings\")\n",
    "\n",
    "from leagues import settings\n",
    "settings.DATABASES['default']['NAME'] = PROJECT_PATH+'/db.sqlite3'\n",
    "\n",
    "import django\n",
    "django.setup()\n",
    "\n",
    "from scheduler.models import *\n",
    "from common.functions import distanceInKmByGPS\n",
    "season = Season.objects.filter(nicename=\"Imported: Benchmark Season\").first()\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from django.db.models import Count, F, Value\n",
    "games = Game.objects.filter(season=season)\n",
    "df = pd.DataFrame.from_records(games.values())\n",
    "games = Game.objects.filter(season=season).annotate(\n",
    "    home=F('homeTeam__shortname'),\n",
    "    away=F('awayTeam__shortname'),\n",
    "    home_lat=F('homeTeam__latitude'),\n",
    "    home_lon=F('homeTeam__longitude'),\n",
    "    home_attr=F('homeTeam__attractivity'),\n",
    "    away_lat=F('awayTeam__latitude'),\n",
    "    away_lon=F('awayTeam__longitude'),\n",
    "    away_attr=F('awayTeam__attractivity')\n",
    ").values()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc191792",
   "metadata": {},
   "source": [
    "#### Dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 248,
   "id": "1e404cf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OneHotEncoder\n",
    "\n",
    "# create dataset\n",
    "df = pd.DataFrame.from_records(games.values())\n",
    "\n",
    "# pivots\n",
    "pivot_homeTeam_mean = df.pivot_table('attendance','homeTeam_id',aggfunc='mean')\n",
    "pivot_homeTeam_max = df.pivot_table('attendance','homeTeam_id',aggfunc='max')\n",
    "\n",
    "# add more features\n",
    "df['weekday'] = df.apply(lambda r: r['date'].weekday(), axis=1)\n",
    "df['day'] = df.apply(lambda r: r['date'].day, axis=1)\n",
    "df['month'] = df.apply(lambda r: r['date'].month, axis=1)\n",
    "df['year'] = df.apply(lambda r: r['date'].year, axis=1)\n",
    "df['distance'] = df.apply(lambda r: distanceInKmByGPS(r['home_lon'],r['home_lat'],r['away_lon'],r['away_lat']), axis=1)\n",
    "df['weekend'] = df.apply(lambda r: int(r['weekday'] in [6,7]), axis=1)\n",
    "df['winter_season'] = df.apply(lambda r: int(r['month'] in [1,2,3,10,11,12]), axis=1)\n",
    "df['home_base'] = df.apply(lambda r: pivot_homeTeam_mean.loc[r['homeTeam_id'],'attendance'], axis=1)\n",
    "df['stadium_size'] = df.apply(lambda r: pivot_homeTeam_max.loc[r['homeTeam_id'],'attendance'], axis=1)\n",
    "\n",
    "# one hot encoding\n",
    "ohe_fields = ['time', 'historic_season']\n",
    "\n",
    "for field in ohe_fields:\n",
    "    ohe = OneHotEncoder()\n",
    "    transformed = ohe.fit_transform(df[[field]])\n",
    "    df[ohe.categories_[0]] = transformed.toarray()\n",
    "\n",
    "# sort label to last index\n",
    "cols = list(df.columns)\n",
    "cols.append(cols.pop(cols.index('attendance')))\n",
    "df = df[cols]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 249,
   "id": "e69d24dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Importing Libraries\n",
    "import numpy as np # linear algebra\n",
    "import pandas as pd # data processing\n",
    "import matplotlib.pyplot as plt # plotting library\n",
    "from sklearn.model_selection import train_test_split,cross_val_score, cross_val_predict\n",
    "from sklearn import metrics\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.preprocessing import PolynomialFeatures\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "from sklearn.ensemble import RandomForestRegressor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2ea08e5",
   "metadata": {},
   "source": [
    "#### Train/Test Data - Normalization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 257,
   "id": "74e12f87",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "\n",
    "remove_columns = ['season_id', 'resultEntered', 'reversible', 'reschedule', 'homeGoals', 'awayGoals',\n",
    "                  'homeGoals2', 'awayGoals2', 'homeGoals3', 'awayGoals3', 'home', 'away', 'date', 'time', 'historic_season', 'id', 'homeTeam_id', 'awayTeam_id']\n",
    "feature_cols = list(set(df.columns[:-1]) - set(remove_columns))\n",
    "# feature_cols = ['weekday','weekend','home_base','distance','winter_season']\n",
    "label = 'attendance'\n",
    "\n",
    "\n",
    "X = df[feature_cols]  # Features\n",
    "y = df[label]  # Target variable\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.3, random_state=1)  # 70% training and 30% test"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94ade4b4",
   "metadata": {},
   "source": [
    "#### Decision Tree"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "id": "4c9bdd0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FITTING...done\n",
      "VISUALIZE\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 183,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pydotplus\n",
    "from six import StringIO\n",
    "from sklearn.tree import export_graphviz\n",
    "from sklearn.tree import DecisionTreeRegressor \n",
    "from sklearn.preprocessing import OneHotEncoder\n",
    "\n",
    "\n",
    "# Create Decision Tree classifer object\n",
    "regr = DecisionTreeRegressor(max_depth=5, random_state=1234)\n",
    "\n",
    "# Train Decision Tree Classifer\n",
    "print(\"FITTING...\", end=\"\")\n",
    "regr = regr.fit(X_train, y_train)\n",
    "print(\"done\")\n",
    "\n",
    "# Predict the response for test dataset\n",
    "y_pred = regr.predict(X_test)\n",
    "\n",
    "\n",
    "# %%\n",
    "\n",
    "\n",
    "print(\"VISUALIZE\")\n",
    "dot_data = StringIO()\n",
    "export_graphviz(regr, out_file=dot_data,\n",
    "                filled=True, rounded=True,\n",
    "                special_characters=True, feature_names=feature_cols)\n",
    "graph = pydotplus.graph_from_dot_data(dot_data.getvalue())\n",
    "graph.write_png('attendance.png')\n",
    "# Image(graph.create_png())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3297f84",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "c2e02abe",
   "metadata": {},
   "source": [
    "#### Other Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "id": "3eeb8fa4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Suppport Vector Regression Accuracy:  -0.026734414429896436\n",
      "R2 square: -0.026734414429896436\n",
      "MAE:  3585.035752797511\n",
      "MSE:  36159653.599150375\n"
     ]
    }
   ],
   "source": [
    "from sklearn.svm import SVR\n",
    "from sklearn import metrics\n",
    "regressor= SVR(kernel='rbf')\n",
    "regressor.fit(X_train,y_train)\n",
    "y_pred_svm=regressor.predict(X_test)\n",
    "#y_pred_svm = cross_val_predict(regressor, x, y)\n",
    "mae=metrics.mean_absolute_error(y_test, y_pred_svm)\n",
    "mse=metrics.mean_squared_error(y_test, y_pred_svm)\n",
    "# Printing the metrics\n",
    "print('Suppport Vector Regression Accuracy: ', regressor.score(X_test,y_test))\n",
    "print('R2 square:',metrics.r2_score(y_test, y_pred_svm))\n",
    "print('MAE: ', mae)\n",
    "print('MSE: ', mse)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1899ba5a",
   "metadata": {},
   "source": [
    "#### Correlation Matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "id": "738f39ca",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<AxesSubplot:>"
      ]
     },
     "execution_count": 197,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 30560 characters]",
      "text/plain": [
       "<Figure size 1440x720 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "# GETTING Correllation matrix\n",
    "corr_mat=X_train.corr(method='pearson')\n",
    "plt.figure(figsize=(20,10))\n",
    "sns.heatmap(corr_mat,vmax=1,square=True,annot=True,cmap='cubehelix')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "id": "38f78b1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "X_Train=X_train.values\n",
    "X_Train=np.asarray(X_Train)\n",
    "\n",
    "# Finding normalised array of X_Train\n",
    "X_std=StandardScaler().fit_transform(X_Train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "ab28ec86",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Cumulative explained variance')"
      ]
     },
     "execution_count": 199,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 15152 characters]",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "pca = PCA().fit(X_std)\n",
    "plt.plot(np.cumsum(pca.explained_variance_ratio_))\n",
    "plt.xlim(0,7,1)\n",
    "plt.xlabel('Number of components')\n",
    "plt.ylabel('Cumulative explained variance')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 200,
   "id": "b40d92f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n",
      "  FutureWarning\n",
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/distributions.py:1718: UserWarning: `shade_lowest` is now deprecated in favor of `thresh`. Setting `thresh=0.05`, but please update your code.\n",
      "  warnings.warn(msg, UserWarning)\n",
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n",
      "  FutureWarning\n",
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/distributions.py:1718: UserWarning: `shade_lowest` is now deprecated in favor of `thresh`. Setting `thresh=0.05`, but please update your code.\n",
      "  warnings.warn(msg, UserWarning)\n",
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n",
      "  FutureWarning\n",
      "/home/md/miniconda3/envs/leagues/lib/python3.7/site-packages/seaborn/distributions.py:1718: UserWarning: `shade_lowest` is now deprecated in favor of `thresh`. Setting `thresh=0.05`, but please update your code.\n",
      "  warnings.warn(msg, UserWarning)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(-2.0, 2.0)"
      ]
     },
     "execution_count": 200,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 30156 characters]",
      "text/plain": [
       "<Figure size 576x576 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "sklearn_pca=PCA(n_components=5)\n",
    "X_Train=sklearn_pca.fit_transform(X_std)\n",
    "\n",
    "sns.set(style='darkgrid')\n",
    "f, ax = plt.subplots(figsize=(8, 8))\n",
    "# ax.set_aspect('equal')\n",
    "ax = sns.kdeplot(X_Train[:,0], X_Train[:,1], cmap=\"Greens\",\n",
    "          shade=True, shade_lowest=False)\n",
    "ax = sns.kdeplot(X_Train[:,1], X_Train[:,2], cmap=\"Reds\",\n",
    "          shade=True, shade_lowest=False)\n",
    "ax = sns.kdeplot(X_Train[:,2], X_Train[:,3], cmap=\"Blues\",\n",
    "          shade=True, shade_lowest=False)\n",
    "red = sns.color_palette(\"Reds\")[-2]\n",
    "blue = sns.color_palette(\"Blues\")[-2]\n",
    "green = sns.color_palette(\"Greens\")[-2]\n",
    "ax.text(0.5, 0.5, \"2nd and 3rd Projection\", size=12, color=blue)\n",
    "ax.text(-4, 0.0, \"1st and 3rd Projection\", size=12, color=red)\n",
    "ax.text(2, 0, \"1st and 2nd Projection\", size=12, color=green)\n",
    "plt.xlim(-6,5)\n",
    "plt.ylim(-2,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 202,
   "id": "aa1bd2a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "number_of_samples = len(y_train)\n",
    "np.random.seed(0)\n",
    "random_indices = np.random.permutation(number_of_samples)\n",
    "num_training_samples = int(number_of_samples*0.75)\n",
    "x_train = X_Train[random_indices[:num_training_samples]]\n",
    "y_train=y[random_indices[:num_training_samples]]\n",
    "x_test=X_Train[random_indices[num_training_samples:]]\n",
    "y_test=y[random_indices[num_training_samples:]]\n",
    "y_Train=list(y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 204,
   "id": "2acb04aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train error = 98.44699684022491 percent in Ridge Regression\n",
      "Test error = 99.98330172684955 percent in Ridge Regression\n"
     ]
    }
   ],
   "source": [
    "from sklearn import linear_model\n",
    "model=linear_model.Ridge()\n",
    "model.fit(x_train,y_train)\n",
    "y_predict=model.predict(x_train)\n",
    "\n",
    "error=0\n",
    "for i in range(len(y_Train)):\n",
    "    error+=(abs(y_Train[i]-y_predict[i])/y_Train[i])\n",
    "train_error_ridge=error/len(y_Train)*100\n",
    "print(\"Train error = \"'{}'.format(train_error_ridge)+\" percent in Ridge Regression\")\n",
    "\n",
    "Y_test=model.predict(x_test)\n",
    "y_Predict=list(y_test)\n",
    "\n",
    "error=0\n",
    "for i in range(len(y_test)):\n",
    "    error+=(abs(y_Predict[i]-Y_test[i])/y_Predict[i])\n",
    "test_error_ridge=error/len(Y_test)*100\n",
    "print(\"Test error = \"'{}'.format(test_error_ridge)+\" percent in Ridge Regression\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 206,
   "id": "10001f77",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'Residual plot in Ridge Regression')"
      ]
     },
     "execution_count": 206,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 36284 characters]",
      "text/plain": [
       "<Figure size 432x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib\n",
    "matplotlib.rcParams['figure.figsize'] = (6.0, 6.0)\n",
    "\n",
    "preds = pd.DataFrame({\"preds\":model.predict(x_train), \"true\":y_train})\n",
    "preds[\"residuals\"] = preds[\"true\"] - preds[\"preds\"]\n",
    "preds.plot(x = \"preds\", y = \"residuals\",kind = \"scatter\")\n",
    "plt.title(\"Residual plot in Ridge Regression\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 208,
   "id": "aef6ee00",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train error = 93.27939871725515 percent in Knn algorithm\n",
      "Test error = 34.00485323676349 percent in knn algorithm\n"
     ]
    }
   ],
   "source": [
    "from sklearn import neighbors\n",
    "n_neighbors=5\n",
    "knn=neighbors.KNeighborsRegressor(n_neighbors,weights='uniform')\n",
    "knn.fit(x_train,y_train)\n",
    "y1_knn=knn.predict(x_train)\n",
    "y1_knn=list(y1_knn)\n",
    "\n",
    "error=0\n",
    "for i in range(len(y_train)):\n",
    "    error+=(abs(y1_knn[i]-y_Train[i])/y_Train[i])\n",
    "train_error_knn=error/len(y_Train)*100\n",
    "print(\"Train error = \"+'{}'.format(train_error_knn)+\" percent\"+\" in Knn algorithm\")\n",
    "\n",
    "y2_knn=knn.predict(x_test)\n",
    "y2_knn=list(y2_knn)\n",
    "error=0\n",
    "for i in range(len(y_test)):\n",
    "    error+=(abs(y2_knn[i]-Y_test[i])/Y_test[i])\n",
    "test_error_knn=error/len(Y_test)*100\n",
    "print(\"Test error = \"'{}'.format(test_error_knn)+\" percent\"+\" in knn algorithm\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "id": "d141476e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train error = 98.42901599605693 percent in Bayesian Regression\n",
      "Test error = 2.6273348309846623 percent in Bayesian Regression\n"
     ]
    }
   ],
   "source": [
    "reg = linear_model.BayesianRidge()\n",
    "reg.fit(x_train,y_train)\n",
    "y1_reg=reg.predict(x_train)\n",
    "y1_reg=list(y1_reg)\n",
    "y2_reg=reg.predict(x_test)\n",
    "y2_reg=list(y2_reg)\n",
    "\n",
    "error=0\n",
    "for i in range(len(y_train)):\n",
    "    error+=(abs(y1_reg[i]-y_Train[i])/y_Train[i])\n",
    "train_error_bay=error/len(y_Train)*100\n",
    "print(\"Train error = \"+'{}'.format(train_error_bay)+\" percent\"+\" in Bayesian Regression\")\n",
    "\n",
    "error=0\n",
    "for i in range(len(y_test)):\n",
    "    error+=(abs(y2_reg[i]-Y_test[i])/Y_test[i])\n",
    "test_error_bay=(error/len(Y_test))*100\n",
    "print(\"Test error = \"+'{}'.format(test_error_bay)+\" percent\"+\" in Bayesian Regression\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 236,
   "id": "cc4ef924",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train error = 45.1440475751096 percent in Decision Tree Regressor\n",
      "Test error = 115.23229120765764 percent in Decision Tree Regressor\n"
     ]
    }
   ],
   "source": [
    "from sklearn.tree import DecisionTreeRegressor \n",
    "\n",
    "dec = DecisionTreeRegressor(max_depth=5, random_state=1234)\n",
    "dec.fit(X_train,y_train)\n",
    "y1_dec=dec.predict(X_train)\n",
    "y1_dec=list(y1_dec)\n",
    "y2_dec=dec.predict(X_test)\n",
    "y2_dec=list(y2_dec)\n",
    "\n",
    "error=0\n",
    "for i,v in enumerate(y_train):\n",
    "    error+=(abs(y1_dec[i]-v)/v)\n",
    "train_error_tree=error/len(y_train)*100\n",
    "print(\"Train error = \"+'{}'.format(train_error_tree)+\" percent\"+\" in Decision Tree Regressor\")\n",
    "\n",
    "error=0\n",
    "for i,v in enumerate(y_test):\n",
    "    error+=(abs(y1_dec[i]-v)/v)\n",
    "test_error_tree=error/len(y_test)*100\n",
    "print(\"Test error = \"'{}'.format(test_error_tree)+\" percent in Decision Tree Regressor\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 240,
   "id": "f8371c65",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mutiple Linear Regression Accuracy:  0.3760362035902819\n",
      "Cross-Predicted(KFold) Mutiple Linear Regression Accuracy:  0.26323368310834494\n"
     ]
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "lin_reg.fit(X_train,y_train)\n",
    "\n",
    "#Predicting the SalePrices using test set \n",
    "y_pred_lr = lin_reg.predict(X_test)\n",
    "\n",
    "#Mutiple Linear Regression Accuracy with test set\n",
    "accuracy_lf = metrics.r2_score(y_test, y_pred_lr)\n",
    "print('Mutiple Linear Regression Accuracy: ', accuracy_lf)\n",
    "\n",
    "#Predicting the SalePrice using cross validation (KFold method)\n",
    "y_pred_kf_lr = cross_val_predict(lin_reg, X, y, cv=10 )\n",
    "\n",
    "#Mutiple Linear Regression Accuracy with cross validation (KFold method)\n",
    "accuracy_lf = metrics.r2_score(y, y_pred_kf_lr)\n",
    "print('Cross-Predicted(KFold) Mutiple Linear Regression Accuracy: ', accuracy_lf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 241,
   "id": "1a05e96e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cross-Predicted(KFold) Polynominal Regression Accuracy:  0.2973208431334121\n"
     ]
    }
   ],
   "source": [
    "poly_reg = PolynomialFeatures(degree = 2)\n",
    "X_poly = poly_reg.fit_transform(X)\n",
    "lin_reg_pl = LinearRegression()\n",
    "\n",
    "#Predicting the SalePrice using cross validation (KFold method)\n",
    "y_pred_pl = cross_val_predict(lin_reg_pl, X_poly, y, cv=10 )\n",
    "#Polynominal Regression Accuracy with cross validation\n",
    "accuracy_pl = metrics.r2_score(y, y_pred_pl)\n",
    "print('Cross-Predicted(KFold) Polynominal Regression Accuracy: ', accuracy_pl)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 242,
   "id": "3002f71b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Decision Tree Regression Accuracy:  0.41316821537538995\n",
      "Cross-Predicted(KFold) Decision Tree Regression Accuracy:  0.43545963056661785\n"
     ]
    }
   ],
   "source": [
    "dt_regressor = DecisionTreeRegressor(random_state = 0)\n",
    "dt_regressor.fit(X_train,y_train)\n",
    "\n",
    "#Predicting the SalePrices using test set \n",
    "y_pred_dt = dt_regressor.predict(X_test)\n",
    "\n",
    "#Decision Tree Regression Accuracy with test set\n",
    "print('Decision Tree Regression Accuracy: ', dt_regressor.score(X_test,y_test))\n",
    "\n",
    "#Predicting the SalePrice using cross validation (KFold method)\n",
    "y_pred_dt = cross_val_predict(dt_regressor, X, y, cv=10 )\n",
    "#Decision Tree Regression Accuracy with cross validation\n",
    "accuracy_dt = metrics.r2_score(y, y_pred_dt)\n",
    "print('Cross-Predicted(KFold) Decision Tree Regression Accuracy: ', accuracy_dt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 243,
   "id": "45e08026",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Random Forest Regression Accuracy:  0.5152096358767789\n",
      "Cross-Predicted(KFold) Random Forest Regression Accuracy:  0.5008508177441224\n"
     ]
    }
   ],
   "source": [
    "rf_regressor = RandomForestRegressor(n_estimators = 300 ,  random_state = 0)\n",
    "rf_regressor.fit(X_train,y_train)\n",
    "\n",
    "#Predicting the SalePrices using test set \n",
    "y_pred_rf = rf_regressor.predict(X_test)\n",
    "\n",
    "#Random Forest Regression Accuracy with test set\n",
    "print('Random Forest Regression Accuracy: ', rf_regressor.score(X_test,y_test))\n",
    "\n",
    "#Predicting the SalePrice using cross validation (KFold method)\n",
    "y_pred_rf = cross_val_predict(rf_regressor, X, y, cv=10 )\n",
    "\n",
    "#Random Forest Regression Accuracy with cross validation\n",
    "accuracy_rf = metrics.r2_score(y, y_pred_rf)\n",
    "print('Cross-Predicted(KFold) Random Forest Regression Accuracy: ', accuracy_rf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 245,
   "id": "0de49b8a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 18692 characters]",
      "text/plain": [
       "<Figure size 1080x720 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "ranking = np.argsort(-rf_regressor.feature_importances_)\n",
    "f, ax = plt.subplots(figsize=(15, 10))\n",
    "sns.barplot(x=rf_regressor.feature_importances_[ranking], y=X_train.columns.values[ranking], orient='h')\n",
    "ax.set_xlabel(\"feature importance\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 246,
   "id": "eff9fa74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mutiple Linear Regression Accuracy:  0.3760362035902819\n",
      "Cross-Predicted(KFold) Mutiple Linear Regression Accuracy:  0.26323368310834494\n"
     ]
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "lin_reg.fit(X_train,y_train)\n",
    "\n",
    "#Predicting the SalePrices using test set \n",
    "y_pred_lr = lin_reg.predict(X_test)\n",
    "\n",
    "#Mutiple Linear Regression Accuracy with test set\n",
    "accuracy_lf = metrics.r2_score(y_test, y_pred_lr)\n",
    "print('Mutiple Linear Regression Accuracy: ', accuracy_lf)\n",
    "\n",
    "#Predicting the SalePrice using cross validation (KFold method)\n",
    "y_pred_kf_lr = cross_val_predict(lin_reg, X, y, cv=10 )\n",
    "\n",
    "#Mutiple Linear Regression Accuracy with cross validation (KFold method)\n",
    "accuracy_lf = metrics.r2_score(y, y_pred_kf_lr)\n",
    "print('Cross-Predicted(KFold) Mutiple Linear Regression Accuracy: ', accuracy_lf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "470425b6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.13 ('leagues')",
   "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.13"
  },
  "vscode": {
   "interpreter": {
    "hash": "a07b7f3079ca8c056705d3c757c4f3f92f9509f33eeab9ad5420dacec37bc01a"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
