{"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":"## Football Match Probability Prediction\n\n**Competition Description**\n\nFootball has been at the heart of data science for more than a decade. If today's algorithms focus on event detection, player style, or team analysis, predicting the results of a match stays an open challenge.\n\nPredicting the outcomes of a match between two teams depends mostly (but not only) on their current form. The form of a team can be viewed as their recent sequence of results versus the other teams. So match probabilities between two teams can be different given their calendar.\n\nThis competition is about predicting the probabilities of more than 150000 match outcomes using the recent sequence of 10 matches of the teams.\n\n**Introduction**\n\nThe goal of this notebook is to develop a LSTM model.\nIt may be improved greatly by more feature engineering and other stuffs.\n\n> **In case you fork/copy/like this notebook:**\n> **Upvote it s'il te plaît/Per favore/Please**\n\nThis notebook was inspired (not copied) by the work of: \nhttps://www.kaggle.com/igorkf/football-match-probability-prediction-lstm-starter","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom sklearn.model_selection import KFold, RepeatedKFold\nfrom sklearn.preprocessing import RobustScaler, LabelEncoder\nfrom sklearn.metrics import accuracy_score, log_loss\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":{"_cell_guid":"c6c6ebe4-3bf5-4a40-8f8e-3f065ecd9e16","_uuid":"920e6d1a-69cf-46e8-a78b-24f7fe780f73","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:01.750255Z","iopub.execute_input":"2022-05-07T12:51:01.750645Z","iopub.status.idle":"2022-05-07T12:51:08.674296Z","shell.execute_reply.started":"2022-05-07T12:51:01.750566Z","shell.execute_reply":"2022-05-07T12:51:08.673243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#loading the data\ntrain = pd.read_csv('../input/football-match-probability-prediction/train.csv')\ntest = pd.read_csv('../input/football-match-probability-prediction/test.csv')","metadata":{"_cell_guid":"e5fbcac1-440c-4d84-8f6f-6ef0f1102c70","_uuid":"f9cd6673-ccc8-4e4c-bce0-c4e7e1d8e98a","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:08.680000Z","iopub.execute_input":"2022-05-07T12:51:08.680631Z","iopub.status.idle":"2022-05-07T12:51:18.935878Z","shell.execute_reply.started":"2022-05-07T12:51:08.680583Z","shell.execute_reply":"2022-05-07T12:51:18.934751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 = 3 #number of classes (home, draw, away)","metadata":{"_cell_guid":"72e32380-622d-40ce-b35a-674120f981b1","_uuid":"9bc24db5-b55a-4e16-87c3-ce6b4cd8a552","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:18.937833Z","iopub.execute_input":"2022-05-07T12:51:18.938195Z","iopub.status.idle":"2022-05-07T12:51:18.946500Z","shell.execute_reply.started":"2022-05-07T12:51:18.938146Z","shell.execute_reply":"2022-05-07T12:51:18.943305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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_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":{"_cell_guid":"fa41a07c-c823-4716-8666-21f3f8cc12ed","_uuid":"daed24ca-8f78-4419-b19f-3b97d78f29f7","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:18.950412Z","iopub.execute_input":"2022-05-07T12:51:18.950823Z","iopub.status.idle":"2022-05-07T12:51:21.964325Z","shell.execute_reply.started":"2022-05-07T12:51:18.950757Z","shell.execute_reply":"2022-05-07T12:51:21.963310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"_cell_guid":"fe6715ba-250e-4a67-bc76-f046ba57b793","_uuid":"7b65ce25-5a33-4fb8-b04b-0f288ea3d9bb","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:21.965913Z","iopub.execute_input":"2022-05-07T12:51:21.966294Z","iopub.status.idle":"2022-05-07T12:51:23.154981Z","shell.execute_reply.started":"2022-05-07T12:51:21.966250Z","shell.execute_reply":"2022-05-07T12:51:23.153925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Target, train and test shape\nprint(f\"Target: {train_y.shape} \\n Train shape: {train_x.shape} \\n Test: {test_x.shape}\")\nprint(f\"Column names: {list(train_x.columns)}\")","metadata":{"_cell_guid":"9ab58872-8c97-4c9a-a110-a55588e0f29f","_uuid":"9c748333-e838-48d8-88f0-33ef0051e57e","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:23.156530Z","iopub.execute_input":"2022-05-07T12:51:23.156854Z","iopub.status.idle":"2022-05-07T12:51:23.166133Z","shell.execute_reply.started":"2022-05-07T12:51:23.156815Z","shell.execute_reply":"2022-05-07T12:51:23.164002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_x.head()","metadata":{"_cell_guid":"9dda4bc6-19b1-40f4-bab6-ca33dae90f12","_uuid":"e45561e1-2c45-4bb8-8b20-70aa386fc82a","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:23.167949Z","iopub.execute_input":"2022-05-07T12:51:23.168577Z","iopub.status.idle":"2022-05-07T12:51:23.213492Z","shell.execute_reply.started":"2022-05-07T12:51:23.168536Z","shell.execute_reply":"2022-05-07T12:51:23.212265Z"},"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_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":{"_cell_guid":"46437c51-e209-4f27-8d53-1bf0e8547fc4","_uuid":"c316690b-dbb6-45f2-882c-18bcb932af61","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:51:23.214905Z","iopub.execute_input":"2022-05-07T12:51:23.215848Z","iopub.status.idle":"2022-05-07T12:52:48.449300Z","shell.execute_reply.started":"2022-05-07T12:51:23.215802Z","shell.execute_reply":"2022-05-07T12:52:48.447117Z"},"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-07T12:52:48.451001Z","iopub.execute_input":"2022-05-07T12:52:48.451642Z","iopub.status.idle":"2022-05-07T12:52:49.066934Z","shell.execute_reply.started":"2022-05-07T12:52:48.451592Z","shell.execute_reply":"2022-05-07T12:52:49.065913Z"},"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-07T12:52:49.068449Z","iopub.execute_input":"2022-05-07T12:52:49.068759Z","iopub.status.idle":"2022-05-07T12:52:51.115629Z","shell.execute_reply.started":"2022-05-07T12:52:49.068715Z","shell.execute_reply":"2022-05-07T12:52:51.114649Z"},"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-07T12:52:51.117170Z","iopub.execute_input":"2022-05-07T12:52:51.117527Z","iopub.status.idle":"2022-05-07T12:52:53.584756Z","shell.execute_reply.started":"2022-05-07T12:52:51.117484Z","shell.execute_reply":"2022-05-07T12:52:53.583579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Train array shape: {x_train.shape} \\nTest array shape: {x_test.shape}\")","metadata":{"_cell_guid":"bedd04b7-cf54-4289-b3c9-b6086f90a580","_uuid":"9adbb500-7f82-41be-aa8f-f19c9291c4e9","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:53.586250Z","iopub.execute_input":"2022-05-07T12:52:53.587507Z","iopub.status.idle":"2022-05-07T12:52:53.594252Z","shell.execute_reply.started":"2022-05-07T12:52:53.587460Z","shell.execute_reply":"2022-05-07T12:52:53.593180Z"},"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":{"_cell_guid":"40d047c0-ca6f-4bdc-af0f-17e0d1f843f5","_uuid":"129f90f7-7744-488c-9e61-b49bb2c90992","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:53.599639Z","iopub.execute_input":"2022-05-07T12:52:53.599937Z","iopub.status.idle":"2022-05-07T12:52:53.643796Z","shell.execute_reply.started":"2022-05-07T12:52:53.599895Z","shell.execute_reply":"2022-05-07T12:52:53.642848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# encoding away: 0 draw: 1 home: 2 \nprint(encoded_y[:10,])\n# Order: away, draw, home\nprint(dummy_y[:10,])","metadata":{"_cell_guid":"6a9dcfac-a3a7-40a2-b7c1-c515319b7e0c","_uuid":"f66ba6cb-16e0-4560-a345-e5a38b5ed82c","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:53.645657Z","iopub.execute_input":"2022-05-07T12:52:53.646085Z","iopub.status.idle":"2022-05-07T12:52:53.656973Z","shell.execute_reply.started":"2022-05-07T12:52:53.646023Z","shell.execute_reply":"2022-05-07T12:52:53.655740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This is similar to the model of \"igorkf\" (Good, loss ~ 0.999)\ndef model_2():\n    x_input = layers.Input(shape=x_train.shape[1:])\n    # x = layers.Masking(mask_value=MASK, input_shape=(x_train.shape[1:]))(x_input)\n    x = layers.Bidirectional(tf.compat.v1.keras.layers.CuDNNLSTM(16, return_sequences=True))(x_input) #(x)\n    x = layers.Dropout(0.5)(x)  \n    x = layers.Bidirectional(tf.compat.v1.keras.layers.CuDNNLSTM(8, return_sequences=True))(x)\n    x = layers.Dropout(0.5)(x)\n    x = layers.Flatten()(x)\n    # output\n    output = layers.Dense(CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input],outputs=[output])\n\n    return model","metadata":{"_cell_guid":"da442908-1692-4121-b108-ebd4141c4d4f","_uuid":"8f733748-8539-4dff-9db7-88edd1e41bdf","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:53.658544Z","iopub.execute_input":"2022-05-07T12:52:53.658763Z","iopub.status.idle":"2022-05-07T12:52:53.671337Z","shell.execute_reply.started":"2022-05-07T12:52:53.658735Z","shell.execute_reply":"2022-05-07T12:52:53.670243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Choose your model\nmodel = model_2()\nmodel.summary()","metadata":{"_cell_guid":"d48d09c0-c867-4d6c-9edb-9174b243cf4f","_uuid":"43445b36-d540-4621-b921-efbff25a5a48","jupyter":{"outputs_hidden":false},"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:53.673948Z","iopub.execute_input":"2022-05-07T12:52:53.675249Z","iopub.status.idle":"2022-05-07T12:52:57.208747Z","shell.execute_reply.started":"2022-05-07T12:52:53.675200Z","shell.execute_reply":"2022-05-07T12:52:57.207726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_model(\n    model, \n    to_file='Football_Prob_Model.png', \n    show_shapes=True,\n    show_layer_names=True\n)","metadata":{"_cell_guid":"efb6e5f5-4590-4ea3-bf8b-afe761843ee4","_uuid":"8a324a9c-628d-4173-b87f-c425a194d954","jupyter":{"outputs_hidden":false},"scrolled":true,"collapsed":false,"execution":{"iopub.status.busy":"2022-05-07T12:52:57.210789Z","iopub.execute_input":"2022-05-07T12:52:57.211028Z","iopub.status.idle":"2022-05-07T12:52:58.071140Z","shell.execute_reply.started":"2022-05-07T12:52:57.210998Z","shell.execute_reply":"2022-05-07T12:52:58.070009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07T12:52:58.073237Z","iopub.execute_input":"2022-05-07T12:52:58.073606Z","iopub.status.idle":"2022-05-07T12:52:58.081885Z","shell.execute_reply.started":"2022-05-07T12:52:58.073556Z","shell.execute_reply":"2022-05-07T12:52:58.080811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# N_SPLITS of the traning set for validation using KFold\n# Parameters\nEPOCH = 200\nBATCH_SIZE = 512\nN_SPLITS = 5\nSEED = 42\nVERBOSE = 1\nPATIENCE = EPOCH // 10\n\ntest_preds = []\n\nwith gpu_strategy.scope():\n    # kf = KFold(n_splits=N_SPLITS, random_state=None) # shuffle=True\n    rkf = RepeatedKFold(n_splits=5, n_repeats=10, random_state=SEED)\n    for fold, (train_idx, test_idx) in enumerate(rkf.split(x_train, dummy_y)):\n        print('-'*15, '>', f'Fold {fold+1}/{N_SPLITS * 10}', '<', '-'*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        model = model_2()\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        # Predictions\n        test_preds.append(model.predict(x_test).squeeze())\n        \n","metadata":{"execution":{"iopub.status.busy":"2022-05-07T12:52:58.084264Z","iopub.execute_input":"2022-05-07T12:52:58.084958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = sum(test_preds)/len(test_preds)\n\n# away, draw, home\nsubmission = pd.DataFrame(predictions,columns=['away', 'draw', 'home'])\n\n# Round\nround_num = False\nif round_num:\n    submission = submission.round(2)\n    submission['draw'] = 1 - (submission['home'] + submission['away'])  \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":{"_cell_guid":"daf73b19-9b2b-426f-a75a-eb1842f15261","_uuid":"fbc22907-d44b-4d98-a63e-7308371f2575","jupyter":{"outputs_hidden":false},"collapsed":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission[['id', 'home', 'away', 'draw']].head()","metadata":{"_cell_guid":"a7b164c3-f7d6-47a8-b6a6-b84ebb382b4d","_uuid":"a5aeb080-c652-4e2c-9476-e662c51ff731","jupyter":{"outputs_hidden":false},"collapsed":false,"trusted":true},"execution_count":null,"outputs":[]}]}