{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Private test score solution: 0.99129\nThis notebook is a modified version of Fernando Seraquevence notebook https://www.kaggle.com/code/seraquevence/top-5-football-prob-prediction-lstm-v02-gpu\n\n## Features:\n- match: is cup\n- home/away history features: \n    - original: ['is_play_home', 'is_cup', 'goal', 'opponent_goal', 'rating', 'opponent_rating','match_DIFF_day','SAME_coaX', 'SAME_leaG', 'ELO_rating', 'DiffELO_rating']\n    - added: ['ELO_ratingv2' (from Elo equation), 'ELO_ratingv3' (difference)]\n\n## Best models architecture:\n- 2 BILSTM layer + denselayer\n- 2 BIGRU layer + denselayer\n- denselayer + 1 Transformer block + denselayer (No improvement using multi-head / multiples Transformer block, did not find correct positionnal embedding function)\n\n## 3 classes:\n- Using one model from list above -> Public test score between 0.9961-0.997    \n- Multi-model prediction -> Best Public test score: 0.99565, Best Private test score: 0.99151\n\n## 5 or 7 classes:\n- Create 5 or 7 classes based on goal differences (https://www.kaggle.com/competitions/football-match-probability-prediction/discussion/314078)\n- Train model above on 5 or 7 classes and add prediction to find 3 classes probs\n- Using one model from list above -> Public test score between 0.99530-0.9961  \n- Multi-model prediction using 4 BILSTM / 4 BIGRU / 3 Transformer -> Public test score: 0.99493, Private test score: 0.99129\n","metadata":{}},{"cell_type":"markdown","source":"## Import modules and loading the data\nFirst let's import modules, the training and the test set. The test set contains the same columns than the training set without the target.","metadata":{"_uuid":"a1e98e57-05f8-42b9-815d-023b303cd789","_cell_guid":"000b4f69-0b86-45f3-9560-8c549acb8e78","trusted":true}},{"cell_type":"code","source":"# Import libraries\n# import gc\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\n#\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import RobustScaler, LabelEncoder\nfrom sklearn.metrics import accuracy_score, log_loss\n#\nimport tensorflow as tf\nfrom tensorflow.keras.utils import plot_model, to_categorical\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, LearningRateScheduler\nfrom tensorflow.keras.optimizers.schedules import ExponentialDecay\nfrom tensorflow.keras import layers","metadata":{"_uuid":"920e6d1a-69cf-46e8-a78b-24f7fe780f73","_cell_guid":"c6c6ebe4-3bf5-4a40-8f8e-3f065ecd9e16","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:09.480094Z","iopub.execute_input":"2022-05-07T13:54:09.480680Z","iopub.status.idle":"2022-05-07T13:54:09.486933Z","shell.execute_reply.started":"2022-05-07T13:54:09.480640Z","shell.execute_reply":"2022-05-07T13:54:09.485841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#loading the data\ntrain = pd.read_csv('/kaggle/input/football-match-probability-prediction/train.csv')\ntest = pd.read_csv('/kaggle/input/football-match-probability-prediction/test.csv')\ntrain_target = pd.read_csv('/kaggle/input/football-match-probability-prediction/train_target_and_scores.csv')\nsubmission = pd.read_csv('/kaggle/input/football-match-probability-prediction/sample_submission.csv')","metadata":{"_uuid":"f9cd6673-ccc8-4e4c-bce0-c4e7e1d8e98a","_cell_guid":"e5fbcac1-440c-4d84-8f6f-6ef0f1102c70","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:09.639336Z","iopub.execute_input":"2022-05-07T13:54:09.639799Z","iopub.status.idle":"2022-05-07T13:54:15.544367Z","shell.execute_reply.started":"2022-05-07T13:54:09.639770Z","shell.execute_reply":"2022-05-07T13:54:15.543675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Parameters\nSet some parameters that will be used later.","metadata":{"_uuid":"ac3c4d94-2456-491c-b634-480be3505386","_cell_guid":"62203296-73b6-416a-b8af-83919edc6721","trusted":true}},{"cell_type":"code","source":"# Set seed\nnp.random.seed(123)\ntf.random.set_seed(123)\n\n#Some parameters\nMASK = -666 # fill NA with -666 (the number of the beast)\nT_HIST = 10 # time history, last 10 games\nCLASS = 7 #number of classes (home, draw, away)\n\nDEBUG = False\n# Run on a small sample of the data\nif DEBUG:\n    train = train[:10000]","metadata":{"_uuid":"9bc24db5-b55a-4e16-87c3-ce6b4cd8a552","_cell_guid":"72e32380-622d-40ce-b35a-674120f981b1","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:15.545936Z","iopub.execute_input":"2022-05-07T13:54:15.546176Z","iopub.status.idle":"2022-05-07T13:54:15.552100Z","shell.execute_reply.started":"2022-05-07T13:54:15.546142Z","shell.execute_reply":"2022-05-07T13:54:15.551400Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_target[\"hg\"] = train_target[\"score\"].apply(lambda x: np.int32(x.split(\"-\")[0]))\ntrain_target[\"ag\"] = train_target[\"score\"].apply(lambda x: np.int32(x.split(\"-\")[1]))\ntrain_target[\"diff\"] = train_target[\"hg\"] - train_target[\"ag\"]\ntrain_target[\"target_cls\"] = 0 + 1*(train_target[\"diff\"]==-2) + 2*(train_target[\"diff\"]==-1) + 3*(train_target[\"diff\"]==0) + 4*(train_target[\"diff\"]==1) + 5*(train_target[\"diff\"]==2) + 6*(train_target[\"diff\"]>2)\ntrain[\"target\"] = train_target[\"target_cls\"]","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:54:15.553147Z","iopub.execute_input":"2022-05-07T13:54:15.553610Z","iopub.status.idle":"2022-05-07T13:54:15.908318Z","shell.execute_reply.started":"2022-05-07T13:54:15.553572Z","shell.execute_reply":"2022-05-07T13:54:15.907594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# exclude matches with no history at date 1 - full of NA (1159 rows excluded)\ntrain.dropna(subset=['home_team_history_match_date_1'], inplace = True)\n# exclude leagues with less than 15 matches: This change has no effect on the final log loss\nif False:\n    train['league_id_count'] = train.groupby('league_id')['id'].transform('count')\n    train = train.loc[train['league_id_count'] > 15]","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:54:15.911974Z","iopub.execute_input":"2022-05-07T13:54:15.912193Z","iopub.status.idle":"2022-05-07T13:54:16.018178Z","shell.execute_reply.started":"2022-05-07T13:54:15.912166Z","shell.execute_reply":"2022-05-07T13:54:16.017430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature Engineering\nThe **most** important part of Machine Learning.","metadata":{"_uuid":"91794a39-6ab8-4fac-bf6a-833de1182b06","_cell_guid":"838bf7ec-34de-46d8-8de9-0c9be9cb1fea","trusted":true}},{"cell_type":"code","source":"# for cols \"date\", change to datatime \nfor col in train.filter(regex='date', axis=1).columns:\n    train[col] = pd.to_datetime(train[col])\n    test[col] = pd.to_datetime(test[col])\n\n# Some feature engineering\ndef add_features(df):\n    for i in range(1, 11): # range from 1 to 10\n        # Feat. difference of days\n        df[f'home_team_history_match_DIFF_day_{i}'] = (df['match_date'] - df[f'home_team_history_match_date_{i}']).dt.days\n        df[f'away_team_history_match_DIFF_days_{i}'] = (df['match_date'] - df[f'away_team_history_match_date_{i}']).dt.days\n    # Feat. difference of scored goals\n        df[f'home_team_history_DIFF_goal_{i}'] = df[f'home_team_history_goal_{i}'] - df[f'home_team_history_opponent_goal_{i}']\n        df[f'away_team_history_DIFF_goal_{i}'] = df[f'away_team_history_goal_{i}'] - df[f'away_team_history_opponent_goal_{i}']\n    # Feat dummy winner x loser\n        df[f'home_winner_{i}'] = np.where(df[f'home_team_history_DIFF_goal_{i}'] > 0, 1., 0.) \n        df[f'home_loser_{i}'] = np.where(df[f'home_team_history_DIFF_goal_{i}'] < 0, 1., 0.)\n        df[f'away_winner_{i}'] = np.where(df[f'away_team_history_DIFF_goal_{i}'] > 0, 1., 0.)\n        df[f'away_loser_{i}'] = np.where(df[f'away_team_history_DIFF_goal_{i}'] < 0, 1., 0.)\n    # Results: multiple nested where # away:0, draw:1, home:2\n        df[f'home_team_result_{i}'] = np.where(df[f'home_team_history_DIFF_goal_{i}'] > 0., 2.,\n                         (np.where(df[f'home_team_history_DIFF_goal_{i}'] == 0., 1,\n                                   np.where(df[f'home_team_history_DIFF_goal_{i}'].isna(), np.nan, 0))))\n        df[f'away_team_result_{i}'] = np.where(df[f'away_team_history_DIFF_goal_{i}'] > 0., 2.,\n                         (np.where(df[f'away_team_history_DIFF_goal_{i}'] == 0., 1.,\n                                   np.where(df[f'away_team_history_DIFF_goal_{i}'].isna(), np.nan, 0.))))\n    # Feat. difference of rating (\"modified\" ELO RATING)\n        df[f'home_team_history_ELO_rating_{i}'] = 1/(1+10**((df[f'home_team_history_opponent_rating_{i}']-df[f'home_team_history_rating_{i}'])/10))\n        df[f'away_team_history_ELO_rating_{i}'] = 1/(1+10**((df[f'away_team_history_opponent_rating_{i}']-df[f'away_team_history_rating_{i}'])/10))\n        df[f'home_team_history_ELO_ratingv2_{i}'] = 1/(1+10**((df[f'home_team_history_opponent_rating_{i}']-df[f'home_team_history_rating_{i}'])/400))\n        df[f'away_team_history_ELO_ratingv2_{i}'] = 1/(1+10**((df[f'away_team_history_opponent_rating_{i}']-df[f'away_team_history_rating_{i}'])/400))\n        df[f'home_team_history_ELO_ratingv3_{i}'] = df[f'home_team_history_rating_{i}']-df[f'home_team_history_opponent_rating_{i}']\n        df[f'away_team_history_ELO_ratingv3_{i}'] = df[f'away_team_history_rating_{i}']-df[f'away_team_history_opponent_rating_{i}']\n        df[f'home_away_team_history_ELO_rating_{i}'] = 1/(1+10**((df[f'away_team_history_rating_{i}']-df[f'home_team_history_rating_{i}'])/10))\n        # df[f'away_team_history_DIFF_rating_{i}'] =  - df[f'away_team_history_opponent_rating_{i}']\n    # Feat. same coach id\n        df[f'home_team_history_SAME_coaX_{i}'] = np.where(df['home_team_coach_id']==df[f'home_team_history_coach_{i}'],1,0)\n        df[f'away_team_history_SAME_coaX_{i}'] = np.where(df['away_team_coach_id']==df[f'away_team_history_coach_{i}'],1,0) \n    # Feat. same league id\n        df[f'home_team_history_SAME_leaG_{i}'] = np.where(df['league_id']==df[f'home_team_history_league_id_{i}'],1,0)\n        df[f'away_team_history_SAME_leaG_{i}'] = np.where(df['league_id']==df[f'away_team_history_league_id_{i}'],1,0) \n    # Fill NA with -666\n    # df.fillna(MASK, inplace = True)\n    return df\n\ntrain = add_features(train)\ntest = add_features(test)","metadata":{"_uuid":"daed24ca-8f78-4419-b19f-3b97d78f29f7","_cell_guid":"fa41a07c-c823-4716-8666-21f3f8cc12ed","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:16.020175Z","iopub.execute_input":"2022-05-07T13:54:16.020687Z","iopub.status.idle":"2022-05-07T13:54:18.510370Z","shell.execute_reply.started":"2022-05-07T13:54:16.020649Z","shell.execute_reply":"2022-05-07T13:54:18.509662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Scaling and Reshape\nThe input/output of the lstm is very trick. It is expected an array of dimensions (Matches/Batch, Time history, Features). I hope I did it right.","metadata":{"_uuid":"0fa67e85-50f7-43af-a9dc-b11c05bcbf8c","_cell_guid":"878d27a4-831a-4a9f-9c9b-275409afc69b","trusted":true}},{"cell_type":"code","source":"# save targets\n# train_id = train['id'].copy()\ntrain_y = train['target'].copy()\n#keep only some features\ntrain_x = train.drop(['target', 'home_team_name', 'away_team_name'], axis=1) #, inplace=True) # is_cup EXCLUDED\n# Exclude all date, league, coach columns\ntrain_x.drop(train.filter(regex='date').columns, axis=1, inplace = True)\ntrain_x.drop(train.filter(regex='league').columns, axis=1, inplace = True)\ntrain_x.drop(train.filter(regex='coach').columns, axis=1, inplace = True)\n#\n# Test set\n# test_id = test['id'].copy()\ntest_x = test.drop(['home_team_name', 'away_team_name'], axis=1)#, inplace=True) # is_cup EXCLUDED\n# Exclude all date, league, coach columns\ntest_x.drop(test.filter(regex='date').columns, axis=1, inplace = True)\ntest_x.drop(test.filter(regex='league').columns, axis=1, inplace = True)\ntest_x.drop(test.filter(regex='coach').columns, axis=1, inplace = True)","metadata":{"_uuid":"7b65ce25-5a33-4fb8-b04b-0f288ea3d9bb","_cell_guid":"fe6715ba-250e-4a67-bc76-f046ba57b793","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:18.511657Z","iopub.execute_input":"2022-05-07T13:54:18.511897Z","iopub.status.idle":"2022-05-07T13:54:19.495865Z","shell.execute_reply.started":"2022-05-07T13:54:18.511866Z","shell.execute_reply":"2022-05-07T13:54:19.495132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Store feature names\n# feature_names = list(train.columns)\n# Pivot dataframe to create an input array for the LSTM network\nfeature_groups = [\"home_team_history_is_play_home\", \"home_team_history_is_cup\",\n    \"home_team_history_goal\", \"home_team_history_opponent_goal\",\n    \"home_team_history_rating\", \"home_team_history_opponent_rating\",  \n    \"away_team_history_is_play_home\", \"away_team_history_is_cup\",\n    \"away_team_history_goal\", \"away_team_history_opponent_goal\",\n    \"away_team_history_rating\", \"away_team_history_opponent_rating\",  \n    \"home_team_history_match_DIFF_day\", \"away_team_history_match_DIFF_days\",\n    \"home_team_history_DIFF_goal\",\"away_team_history_DIFF_goal\",\n    \"home_team_history_ELO_rating\",\"away_team_history_ELO_rating\", \n    \"home_team_history_ELO_ratingv2\", \"away_team_history_ELO_ratingv2\",\n    \"home_team_history_ELO_ratingv3\", \"away_team_history_ELO_ratingv3\",\n    \"home_away_team_history_ELO_rating\",\n    \"home_team_history_SAME_coaX\", \"away_team_history_SAME_coaX\",\n    \"home_team_history_SAME_leaG\", \"away_team_history_SAME_leaG\",\n    \"home_team_result\", \"away_team_result\",\n    \"home_winner\", \"home_loser\", \"away_winner\", \"away_loser\"]      \n# Pivot dimension (id*features) x time_history\ntrain_x_pivot = pd.wide_to_long(train_x, stubnames=feature_groups, \n                i=['id','is_cup'], j='time', sep='_', suffix='\\d+')\ntest_x_pivot = pd.wide_to_long(test_x, stubnames=feature_groups, \n                i=['id','is_cup'], j='time', sep='_', suffix='\\d+')\n#\nprint(f\"Train pivot shape: {train_x_pivot.shape}\")  \nprint(f\"Test pivot shape: {test_x_pivot.shape}\") ","metadata":{"_uuid":"c316690b-dbb6-45f2-882c-18bcb932af61","_cell_guid":"46437c51-e209-4f27-8d53-1bf0e8547fc4","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:54:19.497206Z","iopub.execute_input":"2022-05-07T13:54:19.497474Z","iopub.status.idle":"2022-05-07T13:55:41.648411Z","shell.execute_reply.started":"2022-05-07T13:54:19.497424Z","shell.execute_reply":"2022-05-07T13:55:41.647715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# drop features\ncoldrop = [\"home_team_history_DIFF_goal\", \"away_team_history_DIFF_goal\", \"home_winner\", \"away_winner\",\"home_loser\", \"away_loser\", \"home_team_result\", \"away_team_result\"]\n\ntrain_x_pivot = train_x_pivot.drop(coldrop,axis = 1)\ntest_x_pivot = test_x_pivot.drop(coldrop,axis = 1)","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:41.652571Z","iopub.execute_input":"2022-05-07T13:55:41.654614Z","iopub.status.idle":"2022-05-07T13:55:41.908191Z","shell.execute_reply.started":"2022-05-07T13:55:41.654570Z","shell.execute_reply":"2022-05-07T13:55:41.907297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create columns based on index\ntrain_x_pivot = train_x_pivot.reset_index()\ntest_x_pivot = test_x_pivot.reset_index()\n# Deal with the is_cup feature\n# There are NA in 'is_cup'\ntrain_x_pivot=train_x_pivot.fillna({'is_cup':False})\ntrain_x_pivot['is_cup'] = pd.get_dummies(train_x_pivot['is_cup'], drop_first=True)\n#\ntest_x_pivot=test_x_pivot.fillna({'is_cup':False})\ntest_x_pivot['is_cup']= pd.get_dummies(test_x_pivot['is_cup'], drop_first=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:41.909782Z","iopub.execute_input":"2022-05-07T13:55:41.910261Z","iopub.status.idle":"2022-05-07T13:55:42.391232Z","shell.execute_reply.started":"2022-05-07T13:55:41.910193Z","shell.execute_reply":"2022-05-07T13:55:42.390413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Changing the sequence of time from 1...10 to 10...1 improve the model?\n# bidirectional LSTM is used\n\nINV = True\nif INV:\n    # Trying to keep the same id order\n    train_x_pivot.sort_values(by=['time'], inplace = True, ascending=False)\n    # Merge and drop columns\n    train_x_pivot = pd.merge(train_x['id'], train_x_pivot, on=\"id\").drop(['id', 'time'], axis = 1)\n    # Test\n    test_x_pivot.sort_values(by=['time'], inplace = True, ascending=False)\n    test_x_pivot = pd.merge(test_x['id'], test_x_pivot, on=\"id\").drop(['id', 'time'], axis = 1)\n    \n    # x_test_pivot = x_test_pivot.reset_index()\n    # x_test_pivot['time'] = (T_HIST + 1) - x_test_pivot['time']\n    # x_test_pivot.sort_values(by=['time'], inplace = True)\n    # x_test = pd.merge(test_id, x_test_pivot, on=\"id\").drop(['id', 'time'], axis = 1)\n    # x_test = x_test.to_numpy().reshape(-1, T_HIST, x_test.shape[-1])","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:42.394521Z","iopub.execute_input":"2022-05-07T13:55:42.394997Z","iopub.status.idle":"2022-05-07T13:55:43.655071Z","shell.execute_reply.started":"2022-05-07T13:55:42.394955Z","shell.execute_reply":"2022-05-07T13:55:43.654273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train_x_pivot.copy() #drop(['id', 'time'], axis=1)\nx_test = test_x_pivot.copy() #drop(['id', 'time'], axis=1)\n# Fill NA with median\nfill_median = True\nif fill_median:\n    x_train = np.where(np.isnan(x_train), np.nanmedian(x_train, axis=0), x_train)\n    x_test = np.where(np.isnan(x_test), np.nanmedian(x_test, axis=0), x_test)\n\n# Scale features using statistics that are robust to outliers\nRS = RobustScaler()\nx_train = RS.fit_transform(x_train)\nx_test = RS.transform(x_test)\n# Reshape \nx_train = x_train.reshape(-1, T_HIST, x_train.shape[-1])\nx_test = x_test.reshape(-1, T_HIST, x_test.shape[-1])\n\nif False:\n    # Fill NA with MASK\n    x_train = np.nan_to_num(x_train, nan=MASK)\n    x_test = np.nan_to_num(x_test, nan=MASK)\n\n# Back to pandas.dataframe\n# x_train = pd.DataFrame(train, columns=feature_names)\n# x_train = pd.concat([train_id, x_train], axis = 1)\n#\n# x_test = pd.DataFrame(test, columns=feature_names)\n# x_test = pd.concat([test_id, x_test], axis = 1)","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:43.656662Z","iopub.execute_input":"2022-05-07T13:55:43.656961Z","iopub.status.idle":"2022-05-07T13:55:45.715460Z","shell.execute_reply.started":"2022-05-07T13:55:43.656896Z","shell.execute_reply":"2022-05-07T13:55:45.714699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Deal with targets\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(train_y)\nencoded_y = encoder.transform(train_y)\n# convert integers to dummy variables (i.e. one hot encoded)\ndummy_y = to_categorical(encoded_y)\n# \nprint(encoded_y.shape)\nprint(dummy_y.shape)","metadata":{"_uuid":"129f90f7-7744-488c-9e61-b49bb2c90992","_cell_guid":"40d047c0-ca6f-4bdc-af0f-17e0d1f843f5","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:45.716812Z","iopub.execute_input":"2022-05-07T13:55:45.717108Z","iopub.status.idle":"2022-05-07T13:55:45.733912Z","shell.execute_reply.started":"2022-05-07T13:55:45.717073Z","shell.execute_reply":"2022-05-07T13:55:45.733227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Setup GPU\nBelow declare whether to use 1 GPU or multiple GPU. (Change CUDA_VISIBLE_DEVICES to use more GPUs). I am not aware of the impact on speed.","metadata":{}},{"cell_type":"code","source":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\n# USE MULTIPLE GPUS\nif os.environ[\"CUDA_VISIBLE_DEVICES\"].count(',') == 0:\n    gpu_strategy = tf.distribute.get_strategy()\n    print('single strategy')\nelse:\n    gpu_strategy = tf.distribute.MirroredStrategy()\n    print('multiple strategy')","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:45.735039Z","iopub.execute_input":"2022-05-07T13:55:45.735352Z","iopub.status.idle":"2022-05-07T13:55:45.748763Z","shell.execute_reply.started":"2022-05-07T13:55:45.735315Z","shell.execute_reply":"2022-05-07T13:55:45.748016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Make a model\nThe model is a very simple LSTM. Why LSTM? Because we have the time history of the football team. I'm not sure whether it has any influence on the result at least for my football team, losing and winning at random. \nI would try to make a XGBOOST model with aggregated time features and compare the results.","metadata":{"_uuid":"f0fd77a2-0d9c-4fba-ac6d-f879a553bf4c","_cell_guid":"51235a13-fea9-47fd-a2b9-caeccbd0b67f","trusted":true}},{"cell_type":"code","source":"def model_lstm_back(k, dropout):\n    \n    inputs = layers.Input(shape=(x_train.shape[1:]))\n    x = layers.Bidirectional(tf.keras.layers.LSTM(2*k, return_sequences=True))(inputs)\n    x = layers.Dropout(dropout)(x)\n    x = layers.Bidirectional(tf.keras.layers.LSTM(k, return_sequences=True))(x)\n    x = layers.Dropout(dropout)(x)\n    x = layers.Flatten()(x)\n    x = layers.Dense(k, \"relu\")(x)\n    x = layers.Dropout(0.1)(x)\n    outputs = layers.Dense(CLASS, activation='softmax')(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    return model","metadata":{"_uuid":"77fb7a98-c7fb-40e9-87d6-d629076cc8fc","_cell_guid":"0b944518-27e9-46ed-a31a-408b675bdd1b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:45.749947Z","iopub.execute_input":"2022-05-07T13:55:45.750427Z","iopub.status.idle":"2022-05-07T13:55:45.758014Z","shell.execute_reply.started":"2022-05-07T13:55:45.750380Z","shell.execute_reply":"2022-05-07T13:55:45.757206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def model_gru_back(k, dropout):\n    \n    inputs = layers.Input(shape=(x_train.shape[1:]))\n    x = layers.Bidirectional(tf.keras.layers.GRU(2*k, return_sequences=True))(inputs)\n    x = layers.Dropout(dropout)(x)\n    x = layers.Bidirectional(tf.keras.layers.GRU(k, return_sequences=True))(x)\n    x = layers.Dropout(dropout)(x)\n    x = layers.Flatten()(x)\n    x = layers.Dense(k, \"relu\")(x)\n    x = layers.Dropout(0.1)(x)\n    outputs = layers.Dense(CLASS, activation='softmax')(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    return model","metadata":{"_uuid":"8f733748-8539-4dff-9db7-88edd1e41bdf","_cell_guid":"da442908-1692-4121-b108-ebd4141c4d4f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:45.759514Z","iopub.execute_input":"2022-05-07T13:55:45.759997Z","iopub.status.idle":"2022-05-07T13:55:45.769558Z","shell.execute_reply.started":"2022-05-07T13:55:45.759961Z","shell.execute_reply":"2022-05-07T13:55:45.768782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TransformerBlock(layers.Layer):\n    def __init__(self, embed_dim, num_heads, ff_dim, rate=0):\n        super(TransformerBlock, self).__init__()\n        self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)\n        self.ffn = tf.keras.Sequential(\n            [layers.Dense(ff_dim, activation=\"gelu\"), layers.Dense(embed_dim),]\n        )\n        self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)\n        self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)\n        self.dropout1 = layers.Dropout(rate)\n        self.dropout2 = layers.Dropout(rate)\n\n    def call(self, inputs, training):\n        attn_output = self.att(inputs, inputs)\n        attn_output = self.dropout1(attn_output, training=training)\n        out1 = self.layernorm1(inputs + attn_output)\n        ffn_output = self.ffn(out1)\n        ffn_output = self.dropout2(ffn_output, training=training)\n        return self.layernorm2(out1 + ffn_output)\n    \n# class TokenAndPositionEmbedding(layers.Layer):\n#     def __init__(self, maxlen, vocab_size, embed_dim):\n#         super(TokenAndPositionEmbedding, self).__init__()\n#         self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim)\n#         self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)\n\n#     def call(self, x):\n#         maxlen = tf.shape(x)[-1]\n#         positions = tf.range(start=0, limit=maxlen, delta=1)\n#         positions = self.pos_emb(positions)\n#         x = self.token_emb(x)\n#         return x + positions","metadata":{"_uuid":"6d6ccc48-5945-415d-8cf8-c35b7335e743","_cell_guid":"e648e1b0-6967-4cfb-af34-173dc29dea76","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:45.770972Z","iopub.execute_input":"2022-05-07T13:55:45.771225Z","iopub.status.idle":"2022-05-07T13:55:45.781267Z","shell.execute_reply.started":"2022-05-07T13:55:45.771192Z","shell.execute_reply":"2022-05-07T13:55:45.780499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def model_transformer(ff_dim):\n    feat_dim = 16  # Embedding size for each token\n    num_heads = 1  # Number of attention heads\n    \n    inputs = layers.Input(shape=(x_train.shape[1:]))\n    \n    transformer_block = TransformerBlock(feat_dim, num_heads, ff_dim)\n    x = layers.Dense(feat_dim)(inputs)\n    x = transformer_block(x)\n    x = layers.GlobalAveragePooling1D()(x)\n    x = layers.Dropout(0.1)(x)\n    x = layers.Dense(feat_dim, \"relu\")(x)\n    x = layers.Dropout(0.1)(x)\n    outputs = layers.Dense(CLASS, activation=\"softmax\")(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    return model","metadata":{"_uuid":"677f1522-558d-4ca0-8c08-205590b91045","_cell_guid":"8785689a-4fac-4269-9be0-fb80652f93b1","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:56:07.792326Z","iopub.execute_input":"2022-05-07T13:56:07.792885Z","iopub.status.idle":"2022-05-07T13:56:07.799977Z","shell.execute_reply.started":"2022-05-07T13:56:07.792845Z","shell.execute_reply":"2022-05-07T13:56:07.799293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fit the model and a make submission\nOnce the model is fitted we make the **probabilities prediction**. Then we make the submission dataframe with **4 columns**. The columns home, away and draw contain probability while the column id contains the match id.","metadata":{"_uuid":"ea635cb3-5380-4259-ad5f-fd94e9606f26","_cell_guid":"0c123082-ce45-4f81-841d-eb90adea1783","trusted":true}},{"cell_type":"code","source":"# N_SPLITS of the traning set for validation using KFold\n# Parameters\nEPOCH = 200\nBATCH_SIZE = 2048\nN_SPLITS = 5\nSEED = 123\nVERBOSE = 1\nPATIENCE = EPOCH // 10\n\n\nvalid_preds_mean = []\ntest_preds_mean = []\nscore_split = []\n\nwith gpu_strategy.scope():\n    kf = KFold(n_splits=N_SPLITS, random_state=SEED, shuffle=True) # shuffle=True\n\n    for fold, (train_idx, test_idx) in enumerate(kf.split(x_train, dummy_y)):\n        \n        test_preds = []\n        valid_preds = []\n        score_list = []\n        print('-'*15, '>', f'Fold {fold+1}/{N_SPLITS}', '<', '-'*15)\n        X_train, X_valid = x_train[train_idx], x_train[test_idx]\n        Y_train, Y_valid = dummy_y[train_idx], dummy_y[test_idx]\n        ######### Model: CHANGE HERE TOO ################\n        model0 = model_lstm_back(8,0.5)\n        model1 = model_lstm_back(16,0.5)\n        model2 = model_lstm_back(32,0.75)\n        model3 = model_lstm_back(64,0.75)\n        model4 = model_gru_back(8,0.5)\n        model5 = model_gru_back(16,0.5)\n        model6 = model_gru_back(32,0.75)\n        model7 = model_gru_back(64,0.75)\n        model8 = model_transformer(64)\n        model9 = model_transformer(128)\n        model10 = model_transformer(256)\n        \n        models = [model0, model1, model2, model3, model4, model5, model6, model7, model8, model9, model10]\n        \n        for model in models:\n            # It is a multi-class classification problem, categorical_crossentropy is used as the loss function.\n            model.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\",\n                         metrics=[\"accuracy\"])\n            #\n            es = EarlyStopping(monitor='val_loss', patience=PATIENCE, verbose=0, mode='min',\n                               restore_best_weights=True)\n            lr = ReduceLROnPlateau(monitor=\"val_loss\", factor=0.5, patience=10, verbose=0)\n            #\n            model.fit(X_train, Y_train, \n                      validation_data=(X_valid, Y_valid), \n                      epochs=EPOCH,\n                      verbose=VERBOSE,\n                      batch_size=BATCH_SIZE,  \n                      callbacks=[lr, es])\n            # Model validation    \n            y_true = Y_valid.squeeze()\n            y_pred = model.predict(X_valid, batch_size=BATCH_SIZE).squeeze()\n            score1 = log_loss(y_true, y_pred)\n            print(f\"Fold-{fold+1} | OOF LogLoss Score: {score1}\")\n            valid_preds.append(model.predict(X_valid).squeeze())\n            test_preds.append(model.predict(x_test).squeeze())\n            score_list.append(score1)\n            # Predictions\n            test_preds.append(model.predict(x_test).squeeze())\n            # test_preds.append(model.predict(x_test, batch_size=BATCH_SIZE).squeeze().reshape(-1, 1).squeeze())\n            \n        for i in range(len(models)):\n            print(f\"Fold-{fold+1} | Model-{i+1} | OOF LogLoss Score: {np.array(score_list)[i]}\")\n        valid_pred = np.mean(np.array(valid_preds),axis=0)\n        score1 = log_loss(y_true, valid_pred)\n        print(f\"Fold-{fold+1} | MeanPred | OOF LogLoss Score: {score1}\")\n        score_split.append(score1)\n        valid_preds_mean.append(valid_pred)\n        test_preds_mean.append(np.mean(np.array(test_preds),axis=0))\n        # test_preds.append(model.predict(x_test, batch_size=BATCH_SIZE).squeeze().reshape(-1, 1).squeeze())\n\nfor i in range(len(score_split)):\n    print(f\"Fold-{i+1} | OOF LogLoss Score: {score_split[i]}\")\nprint(np.mean(np.array(score_split))) ","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:56:11.369833Z","iopub.execute_input":"2022-05-07T13:56:11.370507Z","iopub.status.idle":"2022-05-07T13:56:54.829312Z","shell.execute_reply.started":"2022-05-07T13:56:11.370440Z","shell.execute_reply":"2022-05-07T13:56:54.828360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = sum(test_preds_mean)/N_SPLITS\npredictions_3cls = np.zeros([len(predictions),3])\npredictions_3cls[:,0] = predictions[:,0] + predictions[:,1] + predictions[:,2]\npredictions_3cls[:,1] = predictions[:,3]\npredictions_3cls[:,2] = predictions[:,4] + predictions[:,5] + predictions[:,6]","metadata":{"execution":{"iopub.status.busy":"2022-05-07T13:55:54.340501Z","iopub.status.idle":"2022-05-07T13:55:54.341201Z","shell.execute_reply.started":"2022-05-07T13:55:54.340945Z","shell.execute_reply":"2022-05-07T13:55:54.340972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# away, draw, home\nsubmission = pd.DataFrame(predictions_3cls,columns=['away', 'draw', 'home'])\n   \n#do not forget the id column\nsubmission['id'] = test[['id']]\n\n#submit!\nsubmission[['id', 'home', 'away', 'draw']].to_csv('submission.csv', index=False)","metadata":{"_uuid":"fbc22907-d44b-4d98-a63e-7308371f2575","_cell_guid":"daf73b19-9b2b-426f-a75a-eb1842f15261","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:54.342618Z","iopub.status.idle":"2022-05-07T13:55:54.343368Z","shell.execute_reply.started":"2022-05-07T13:55:54.343115Z","shell.execute_reply":"2022-05-07T13:55:54.343141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission[['id', 'home', 'away', 'draw']].head()","metadata":{"_uuid":"a5aeb080-c652-4e2c-9476-e662c51ff731","_cell_guid":"a7b164c3-f7d6-47a8-b6a6-b84ebb382b4d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2022-05-07T13:55:54.344667Z","iopub.status.idle":"2022-05-07T13:55:54.345164Z","shell.execute_reply.started":"2022-05-07T13:55:54.344916Z","shell.execute_reply":"2022-05-07T13:55:54.344942Z"},"trusted":true},"execution_count":null,"outputs":[]}]}