{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4d2a8b6c",
   "metadata": {},
   "source": [
    "#### Database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "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",
    "    home_country=F('homeTeam__country'),\n",
    "    away_country=F('awayTeam__country'),\n",
    ").values()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc191792",
   "metadata": {},
   "source": [
    "#### Dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "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",
    "df['early'] = df.apply(lambda r: int(r['time'].replace(':','') < \"1800\"), axis=1)\n",
    "df['before2010'] = df.apply(lambda r: int(r['historic_season'].split('-')[0] < \"2010\"), axis=1)\n",
    "\n",
    "\n",
    "# one hot encoding\n",
    "ohe_fields = ['home_country']\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": 21,
   "id": "1383108f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<string>:6: RuntimeWarning: Converting input from bool to <class 'numpy.uint8'> for compatibility.\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 105232 characters]",
      "text/plain": [
       "<Figure size 1440x1440 with 42 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "df.hist(figsize = (20,20))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2ea08e5",
   "metadata": {},
   "source": [
    "#### Train/Test Data - Normalization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "74e12f87",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "\n",
    "\n",
    "remove_columns = ['season_id', 'resultEntered', 'reversible', 'reschedule', 'homeGoals', 'awayGoals',\n",
    "                  'homeGoals2', 'awayGoals2', 'homeGoals3', 'awayGoals3', 'home', 'away', 'date', 'time',\n",
    "                  'id', 'homeTeam_id', 'awayTeam_id', 'historic_season',\n",
    "                  'home_country','home_lat','home_lon','away_lat','away_lon','away_country']\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": "1899ba5a",
   "metadata": {},
   "source": [
    "#### Correlation Matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "738f39ca",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<AxesSubplot:>"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 209388 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": 26,
   "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": 27,
   "id": "ab28ec86",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Cumulative explained variance')"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 14660 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": 28,
   "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": 28,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 32712 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": null,
   "id": "3ac1fc10",
   "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
}
