{"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":{"_uuid":"7cd960c6-91d4-4ca0-a69a-9e4e520d184a","_cell_guid":"eab67375-a4a9-4e08-bb4a-3c099e21dfa9","trusted":true}},{"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, StratifiedKFold, TimeSeriesSplit\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\n\nimport lightgbm as lgb","metadata":{"_uuid":"920e6d1a-69cf-46e8-a78b-24f7fe780f73","_cell_guid":"c6c6ebe4-3bf5-4a40-8f8e-3f065ecd9e16","collapsed":false,"execution":{"iopub.status.busy":"2022-02-01T15:19:26.012172Z","iopub.execute_input":"2022-02-01T15:19:26.013113Z","iopub.status.idle":"2022-02-01T15:19:33.550109Z","shell.execute_reply.started":"2022-02-01T15:19:26.013044Z","shell.execute_reply":"2022-02-01T15:19:33.549186Z"},"jupyter":{"outputs_hidden":false},"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')\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},"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 = 3 #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},"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)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Train: {train.shape} \\n Submission: {submission.shape}\")\ntrain.head()","metadata":{"_uuid":"f98d00e1-b8db-475f-926b-3f27fc07bc55","_cell_guid":"36d932ff-1cf7-4fa3-97c3-2657a83150a9","collapsed":false,"jupyter":{"outputs_hidden":false},"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_days_{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    # 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    '''\n    # Diff rating\n        df[f'home_team_history_rating_DIFF_{i}'] =  df[f'home_team_history_rating_{i}'] - df[f'home_team_history_opponent_rating_{i}']\n        df[f'away_team_history_rating_DIFF_{i}'] =  df[f'away_team_history_rating_{i}'] - df[f'away_team_history_opponent_rating_{i}']\n        df[f'home_away_team_history_rating_DIFF_{i}'] =  df[f'home_team_history_rating_{i}'] - df[f'away_team_history_rating_{i}']\n    # Div rating\n        df[f'home_team_history_rating_DIV_{i}'] =  df[f'home_team_history_rating_{i}'] / df[f'home_team_history_opponent_rating_{i}']\n        df[f'away_team_history_rating_DIV_{i}'] =  df[f'away_team_history_rating_{i}'] / df[f'away_team_history_opponent_rating_{i}']\n        df[f'home_away_team_history_rating_DIV_{i}'] =  df[f'home_team_history_rating_{i}'] / df[f'away_team_history_rating_{i}']\n     # Features\n        df[f'home_rating_is_play_home_{i}'] =  df[f'home_team_history_rating_{i}'] * df[f'home_team_history_is_play_home_{i}']\n        df[f'away_rating_is_play_away_{i}'] =  df[f'away_team_history_rating_{i}'] * (1 - df[f'away_team_history_is_play_home_{i}'])\n        # df[f'home_away_rating_is_play_where_{i}'] =  df[f'home_rating_is_play_home_{i}'] - df[f'away_rating_is_play_away_{i}']\n    # Feat. count matches\n        df[f'home_count_matches_{i}'] = np.where(df[f'home_team_history_match_date_{i}'].isna(), 0., 1.)\n        df[f'away_count_matches_{i}'] = np.where(df[f'away_team_history_match_date_{i}'].isna(), 0., 1.)\n    '''\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},"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,"execution":{"iopub.status.busy":"2022-02-01T15:19:33.551844Z","iopub.execute_input":"2022-02-01T15:19:33.552117Z","iopub.status.idle":"2022-02-01T15:19:33.583148Z","shell.execute_reply.started":"2022-02-01T15:19:33.552068Z","shell.execute_reply":"2022-02-01T15:19:33.582099Z"},"jupyter":{"outputs_hidden":false},"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":{"_uuid":"9c748333-e838-48d8-88f0-33ef0051e57e","_cell_guid":"9ab58872-8c97-4c9a-a110-a55588e0f29f","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_x.head()","metadata":{"_uuid":"e45561e1-2c45-4bb8-8b20-70aa386fc82a","_cell_guid":"9dda4bc6-19b1-40f4-bab6-ca33dae90f12","collapsed":false,"jupyter":{"outputs_hidden":false},"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_days\", \"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_rating_DIFF\", \"away_team_history_rating_DIFF\", \"home_away_team_history_rating_DIFF\",\n    # \"home_team_history_rating_DIV\", \"away_team_history_rating_DIV\", \"home_away_team_history_rating_DIV\",\n    # \"home_rating_is_play_home\", \"away_rating_is_play_away\", # \"home_away_rating_is_play_where\"\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    # \"home_count_matches\", \"away_count_matches\"\n                 ]      \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,"execution":{"iopub.status.busy":"2022-02-01T15:19:33.584528Z","iopub.execute_input":"2022-02-01T15:19:33.584813Z","iopub.status.idle":"2022-02-01T15:19:33.590424Z","shell.execute_reply.started":"2022-02-01T15:19:33.58477Z","shell.execute_reply":"2022-02-01T15:19:33.589437Z"},"jupyter":{"outputs_hidden":false},"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_count":null,"outputs":[]},{"cell_type":"code","source":"train_x_pivot.head(20)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_x_pivot.head(20)","metadata":{},"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_count":null,"outputs":[]},{"cell_type":"code","source":"# Feature engineering again!!! Group by id, stats over time\ndef add_features_II(df):\n    # df['home_count_matches_csum'] = df.groupby('id')['home_count_matches'].cumsum()\n    # df['away_count_matches_csum'] = df.groupby('id')['away_count_matches'].cumsum()\n    # GOALS\n    df['home_team_history_DIFF_goal_perc'] = df.groupby('id')['home_team_history_DIFF_goal'].cumsum()/df.groupby('id')['home_count_matches'].cumsum()\n    df['away_team_history_DIFF_goal_perc'] = df.groupby('id')['away_team_history_DIFF_goal'].cumsum()/df.groupby('id')['away_count_matches'].cumsum()\n    # \n    df['home_team_result_perc'] = df.groupby('id')['home_team_result'].cumsum()/(2*df.groupby('id')['home_count_matches'].cumsum())\n    df['away_team_result_perc'] = df.groupby('id')['away_team_result'].cumsum()/(2*df.groupby('id')['away_count_matches'].cumsum())\n    #    \n    '''\n    # goals\n    df['home_team_history_DIFF_goal_csum'] = df.groupby('id')['home_team_history_DIFF_goal'].cumsum()\n    df['away_team_history_DIFF_goal_csum'] = df.groupby('id')['away_team_history_DIFF_goal'].cumsum()\n    # df['home_team_hist_goal_csum'] = df.groupby('id')['home_team_history_goal'].cumsum()\n    # df['home_team_hist_opp_goal_csum'] = df.groupby('id')['home_team_history_opponent_goal'].cumsum()\n    # df['away_team_hist_goal_csum'] = df.groupby('id')['away_team_history_goal'].cumsum()\n    # df['away_team_hist_opp_goal_csum'] = df.groupby('id')['away_team_history_opponent_goal'].cumsum()\n    # rating\n    df['home_team_hist_rat_mean'] = df.groupby('id')['home_team_history_rating'].transform('mean')\n    df['away_team_hist_rat_mean'] = df.groupby('id')['away_team_history_rating'].transform('mean')\n    # df['away_team_hist_rat_mean'] = df.groupby('id')['away_team_history_rating'].mean()\n    df['home_away_rat_elo'] = 1/(1+10**((df['away_team_hist_rat_mean']-df['home_team_hist_rat_mean'])/10))\n    # Result (%)\n    df['home_team_result_mean'] = df.groupby('id')['home_team_result'].transform('mean')\n    df['away_team_result_mean'] = df.groupby('id')['away_team_result'].transform('mean')\n    # df['home_team_result_perc'] = df.groupby('id')['home_team_result'].cumsum()\n    # df['away_team_result_perc'] = df.groupby('id')['away_team_result'].cumsum()\n    # df['home_team_result_perc'] = df['home_team_result_perc']/(df['time']*2)\n    # df['away_team_result_perc'] = df['away_team_result_perc']/(df['time']*2)\n    # Lags result if INV = True\n    df['home_team_result_lag1'] = df.groupby('id')['home_team_result'].shift(-1)\n    df['away_team_result_lag1'] = df.groupby('id')['away_team_result'].shift(-1)\n    df['home_team_result_lag2'] = df.groupby('id')['home_team_result'].shift(-2)\n    df['away_team_result_lag2'] = df.groupby('id')['away_team_result'].shift(-2)\n    # dummies results\n    # df = pd.get_dummies(df['home_team_result'])\n    # df = pd.get_dummies(df['away_team_result'])\n    # df['one'] = 1\n    # df['count'] = df.groupby('id').isna()\n    '''\n    return df\n\n# train_x_pivot = add_features_II(train_x_pivot)\n# test_x_pivot = add_features_II(test_x_pivot)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_x_pivot.head(20)\ntest_x_pivot.head(20)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train_x_pivot.drop(['id', 'time'], axis=1).copy()\nx_test = test_x_pivot.drop(['id', 'time'], axis=1).copy()\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_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Train array shape: {x_train.shape} \\nTest array shape: {x_test.shape}\")","metadata":{"_uuid":"9adbb500-7f82-41be-aa8f-f19c9291c4e9","_cell_guid":"bedd04b7-cf54-4289-b3c9-b6086f90a580","collapsed":false,"jupyter":{"outputs_hidden":false},"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},"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":{"_uuid":"f66ba6cb-16e0-4560-a345-e5a38b5ed82c","_cell_guid":"6a9dcfac-a3a7-40a2-b7c1-c515319b7e0c","collapsed":false,"jupyter":{"outputs_hidden":false},"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_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":"# Huge LSTM model -> No good (loss ~ 1.02)\n# RNN : A recurrent model can learn to use a long history of inputs, if it's relevant to the predictions the model is making. \n# Here the model will accumulate internal state for 10 matches, before making a single prediction for the next match.\ndef model_1():\n    x_input = layers.Input(shape=(x_train.shape[-2:]))\n    # x1 = layers.Masking(mask_value=MASK)(x_input)\n    #\n    # x1 = layers.Bidirectional(layers.LSTM(units=512, return_sequences=True))(x_input)\n    # x2 = layers.Bidirectional(layers.LSTM(units=256, return_sequences=True))(x1)\n    # x3 = layers.Bidirectional(layers.LSTM(units=128, return_sequences=True))(x2)\n    #\n    # x4 = layers.Bidirectional(layers.LSTM(units=64, return_sequences=True))(x1)\n    # x5 = layers.Bidirectional(layers.LSTM(units=32, return_sequences=True))(x4)\n    #\n    # z2 = layers.Bidirectional(layers.GRU(units=256, return_sequences=True))(x2)\n    # z3 = layers.Bidirectional(layers.GRU(units=128, return_sequences=True))(Add()([x3, z2]))\n    # x = layers.Concatenate(axis=2)([x3, z2, z3])\n    # x = layers.Bidirectional(layers.LSTM(units=192, return_sequences=True))(x)\n    # Optiver\n    x = layers.Bidirectional(tf.compat.v1.keras.layers.CuDNNLSTM(128, return_sequences=True))(x_input)\n    x = layers.Dropout(0.5)(x)\n    x = layers.Bidirectional(tf.compat.v1.keras.layers.CuDNNLSTM(64, return_sequences=True))(x)\n    x = layers.Dropout(0.5)(x)\n    avg_pool = layers.GlobalAveragePooling1D()(x)\n    max_pool = layers.GlobalMaxPooling1D()(x)\n    conc = layers.concatenate([avg_pool, max_pool])\n    out = layers.Flatten()(conc)\n    x = layers.Dense(units=16, activation='selu')(out)\n    # Output layer must create 3 output values, one for each class.\n    # Activation function is softmax for multi-class classification.\n    x_output = layers.Dense(units=CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input], outputs=[x_output])\n    return model","metadata":{"_uuid":"77fb7a98-c7fb-40e9-87d6-d629076cc8fc","_cell_guid":"0b944518-27e9-46ed-a31a-408b675bdd1b","collapsed":false,"execution":{"iopub.status.busy":"2022-02-01T15:20:22.44192Z","iopub.execute_input":"2022-02-01T15:20:22.442286Z","iopub.status.idle":"2022-02-01T15:20:27.797678Z","shell.execute_reply.started":"2022-02-01T15:20:22.44224Z","shell.execute_reply":"2022-02-01T15:20:27.796701Z"},"jupyter":{"outputs_hidden":false},"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":{"_uuid":"8f733748-8539-4dff-9db7-88edd1e41bdf","_cell_guid":"da442908-1692-4121-b108-ebd4141c4d4f","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# similar to model_2\ndef model_2a():\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.LSTM(16, return_sequences=True)(x_input) #(x)\n    x = layers.Dropout(0.5)(x)  \n    x = layers.LSTM(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":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# standard LSTM model -> Not bad\ndef model_3():\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(layers.LSTM(128, return_sequences=True))(x)\n    x = layers.Dropout(0.5)(x)\n    x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x) \n    x = layers.Dropout(0.5)(x)\n    x = layers.Bidirectional(layers.LSTM(32, return_sequences=True))(x)\n    x = layers.Dropout(0.5)(x)\n    x = layers.Bidirectional(layers.LSTM(16))(x)   #ATTENTION: return sequences False, no Flatten layer\n    x = layers.Dropout(0.5)(x)\n    x = layers.Dense(8, activation='relu')(x)\n    # Output layer must create 3 output values, one for each class.\n    # Activation function is softmax for multi-class classification.\n    output = layers.Dense(CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input],outputs=[output])\n\n    return model","metadata":{"_uuid":"6d6ccc48-5945-415d-8cf8-c35b7335e743","_cell_guid":"e648e1b0-6967-4cfb-af34-173dc29dea76","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# CNN A convolutional model makes predictions based on a fixed-width history, \n# which may lead to better performance than the dense model since it can see how things are changing over time:\nCONV_WIDTH = 3\n\ndef model_4():\n    x_input = layers.Input(shape=x_train.shape[1:])\n    # Shape [batch, time, features] => [batch, CONV_WIDTH, features]\n    # tf.keras.layers.Lambda(lambda x: x[:, -CONV_WIDTH:, :]),\n    # Shape => [batch, 1, conv_units]\n    x = layers.Conv1D(256, activation='relu', kernel_size=(CONV_WIDTH))(x_input)\n    x = layers.Dense(16, activation = 'relu')(x)\n    # Output layer must create 3 output values, one for each class.\n    # Activation function is softmax for multi-class classification.\n    x = layers.Flatten()(x)\n    x = layers.Dropout(0.5)(x)\n    output = layers.Dense(CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input],outputs=[output])\n\n    return model\n#","metadata":{"_uuid":"677f1522-558d-4ca0-8c08-205590b91045","_cell_guid":"8785689a-4fac-4269-9be0-fb80652f93b1","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''#Simple convnet\nMAX_POOL = 3\nCONV_WIDTH = 3\ndef model_5():\n    x_input = layers.Input(shape=x_train.shape[1:])\n    x = layers.Conv1D(32, kernel_size = CONV_WIDTH, padding='same', activation=\"relu\")(x_input)\n    # x = layers.MaxPooling1D(pool_size = MAX_POOL, padding='same')(x)\n    x = layers.Conv1D(16, kernel_size = CONV_WIDTH, padding=\"same\", activation=\"relu\")(x)\n    x = layers.MaxPooling1D(pool_size = MAX_POOL, padding='same')(x)\n    x = layers.Flatten()(x)\n    x = layers.Dropout(0.5)(x)\n    output = layers.Dense(CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input],outputs=[output])\n\n    return model\n'''","metadata":{"_uuid":"0b50bcc9-981d-4a27-be3b-b1d820788b79","_cell_guid":"7db6bbe5-2b85-4783-a3fd-eba3f93cd033","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convolution LSTM1D (no good loss ~ 1.01)\nCONV_WIDTH = 3\n# first add an axis to your data\n# x_train = np.expand_dims(x_train, 2)   \n\ndef model_6():\n    x_input = layers.Input(shape= x_train.shape[1:]) # 4D tensor with shape: (samples, time, channels, rows) # (109779, 10, 1, 30)\n    x = layers.ConvLSTM1D(32,kernel_size=CONV_WIDTH,padding=\"same\",return_sequences=True,activation=\"relu\")(x_input)\n    x = layers.BatchNormalization()(x)\n    x = layers.ConvLSTM1D(16,kernel_size=CONV_WIDTH,padding=\"same\",return_sequences=True,activation=\"relu\")(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Flatten()(x)\n    x = layers.Dropout(0.5)(x)\n    output = layers.Dense(CLASS, activation='softmax')(x)\n    model = Model(inputs=[x_input],outputs=[output])\n\n    return model","metadata":{"_uuid":"a36b56c2-cd15-4940-9ea0-22c1be53b0b6","_cell_guid":"5f42bed7-c0a1-4319-87f1-9b968ec3ca11","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Choose your model\nmodel = model_2()\nmodel.summary()","metadata":{"_uuid":"43445b36-d540-4621-b921-efbff25a5a48","_cell_guid":"d48d09c0-c867-4d6c-9edb-9174b243cf4f","collapsed":false,"jupyter":{"outputs_hidden":false},"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":{"_uuid":"8a324a9c-628d-4173-b87f-c425a194d954","_cell_guid":"efb6e5f5-4590-4ea3-bf8b-afe761843ee4","collapsed":false,"jupyter":{"outputs_hidden":false},"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 = 512\nN_SPLITS = 10 # 5\nSEED = 123\nVERBOSE = 1\nPATIENCE = EPOCH // 10\nFIRST_OOF_ONLY = False\n\ntest_preds = []\n\nwith gpu_strategy.scope():\n    kf = KFold(n_splits=N_SPLITS) # , random_state=SEED, shuffle=True)\n\n    for fold, (train_idx, test_idx) in enumerate(kf.split(x_train, dummy_y)):\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        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        # test_preds.append(model.predict(x_test, batch_size=BATCH_SIZE).squeeze().reshape(-1, 1).squeeze())\n        if FIRST_OOF_ONLY: break\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = sum(test_preds)/N_SPLITS \n\n# away, draw, home\nsub_1 = pd.DataFrame(predictions,columns=['away', 'draw', 'home'])\n\n#do not forget the id column\nsub_1['id'] = test[['id']]\n\n#submit!\n# submission[['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},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# LGB MODEL\n\n# Feature engineering again!!! Group by id, stats over time\ndef agg_features(df):\n    # vol_cols = ['log_return1_realized_volatility', 'log_return2_realized_volatility']\n    # Group by match id\n    df_agg = df.groupby(['id'])[feature_groups].agg(['mean', 'median', 'std', 'max', 'min', 'sum',]).reset_index()\n    # Rename columns joining suffix\n    df_agg.columns = ['_'.join(col) for col in df_agg.columns]\n    return df_agg\n    \ntrain_x_agg = agg_features(train_x_pivot)\ntest_x_agg = agg_features(test_x_pivot)\n\ntrain_x_last = train_x_pivot.loc[train_x_pivot['time'] == 1]\ntest_x_last = test_x_pivot.loc[test_x_pivot['time'] == 1]\n\n# keep order\n# Merge and drop columns\nx_train = pd.merge(train_x_last, train_x_agg, left_on=\"id\", right_on=\"id_\").drop(['id', 'id_', 'time'], axis = 1).copy()\nx_test = pd.merge(test_x_last, test_x_agg, left_on=\"id\", right_on=\"id_\").drop(['id', 'id_', 'time'], axis = 1).copy()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target2int = {'away': 0, 'draw': 1, 'home': 2}\n# encode target\ndummy_y = train_y.map(target2int)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_boost_round = 1000\nSEED = 123\nseed = SEED\nN_SPLITS = 10 # 5\nFIRST_OOF_ONLY: False\n'''\n# Set LGBM hyper parameters\nlgbm_params = { \"objective\":\"multiclass\"\n    , \"boosting_type\":\"gbdt\"\n    , 'num_class':CLASS\n    , 'metric': 'multi_logloss'\n    , \"random_seed\":SEED\n    , \"max_depth\":5\n    , \"colsample_bytree\":0.5\n    , \"subsample\":0.5\n    , \"lambda_l1\":0.1 #reg_alpha(L1)\n    , \"lambda_l2\":0.9 #reg_lambda(L2)\n    , \"learning_rate\":0.1\n    , \"num_leaves\": 5\n} \n'''\n# Params 2\n\nlgbm_params = {\n    \"objective\":\"multiclass\" #\"binary\"\n    , \"boosting_type\":\"gbdt\"\n    , 'num_class':CLASS\n    , 'metric': \"multi_logloss\" #''binary_logloss\n    ,        'learning_rate': 0.05,        \n            'lambda_l1': 2,\n            'lambda_l2': 7,\n            'num_leaves': 400,\n            'min_sum_hessian_in_leaf': 20,\n            'feature_fraction': 0.5,\n            'feature_fraction_bynode': 0.5,\n            'bagging_fraction': 0.5,\n            'bagging_freq': 42,\n            'min_data_in_leaf': 700,\n            'max_depth': 5,\n            'seed': seed,\n            'feature_fraction_seed': seed,\n            'bagging_seed': seed,\n            'drop_seed': seed,\n            'data_random_seed': seed,\n            'verbosity': -1\n        }\n\ntest_preds = []\n\nkf = kf = StratifiedKFold(n_splits=N_SPLITS, random_state=SEED, shuffle=True) # KFold(n_splits=N_SPLITS, random_state=SEED, shuffle=True)\n\nfor fold, (train_idx, test_idx) in enumerate(kf.split(x_train, dummy_y)):\n    print('-'*15, '>', f'Fold {fold+1}/{N_SPLITS}', '<', '-'*15)\n    X_train, X_valid = x_train.iloc[train_idx], x_train.iloc[test_idx]\n    Y_train, Y_valid = dummy_y.iloc[train_idx], dummy_y.iloc[test_idx]\n    # \n    train_dataset = lgb.Dataset(X_train, Y_train) #, categorical_feature = ['is_cup'])\n    val_dataset = lgb.Dataset(X_valid, Y_valid)# , categorical_feature = ['is_cup'])\n    model = lgb.train(params = lgbm_params, \n                        train_set = train_dataset, \n                        valid_sets = [train_dataset, val_dataset], \n                        num_boost_round = num_boost_round, \n                        callbacks=[lgb.early_stopping(stopping_rounds=50)],\n                        verbose_eval = 50)\n    # Model validation    \n    y_true = Y_valid.squeeze()\n    y_pred = model.predict(X_valid).squeeze()\n    score1 = log_loss(y_true, y_pred)\n    print(f\"Fold-{fold+1} | OOF LogLoss Score: {score1}\")\n    # print(roc_auc_score(y_true, y_pred))\n    # Predictions\n    test_preds.append(model.predict(x_test).squeeze())\n    lgb.plot_importance(model,max_num_features=20)\n    if FIRST_OOF_ONLY: break","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = sum(test_preds)/N_SPLITS \n\n# away, draw, home\nsub_2 = pd.DataFrame(predictions,columns=['away', 'draw', 'home'])\n\n#do not forget the id column\nsub_2['id'] = test[['id']]\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# weights\nW = 0.5\nsub_2['away'] = sub_1[['away']]*W + sub_2[['away']]*(1-W)\nsub_2['draw'] = sub_1[['draw']]*W + sub_2[['draw']]*(1-W)\nsub_2['home'] = sub_1[['home']]*W + sub_2[['home']]*(1-W)\n\n# away, draw, home\n# submission = pd.DataFrame(sub_0[1:4]*0.5 + sub_1[1:4]*0.5,columns=['away', 'draw', 'home'])\n    \n#do not forget the id column\n# submission['id'] = sub_1[['id']]\nsub_2[['id', 'home', 'away', 'draw']].to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''# weights\nW = [25, 50, 75, 100]\n# sub = pd.DataFrame(columns=['id','away','draw','home'])\n# sub['id'] = sub_1[['id']]\nfor w in W:\n    submission['away'] = (sub_1[['away']]*w + sub_2[['away']]*(100-w))/100\n    submission['draw'] = (sub_1[['draw']]*w + sub_2[['draw']]*(100-w))/100\n    submission['home'] = (sub_1[['home']]*w + sub_2[['home']]*(100-w))/100\n    file_name = \"submission_\" + str(w) + \".csv\"\n    submission[['id', 'home', 'away', 'draw']].to_csv(file_name, index=False)\n\n# away, draw, home\n# submission = pd.DataFrame(sub_0[1:4]*0.5 + sub_1[1:4]*0.5,columns=['away', 'draw', 'home'])\n    \n#do not forget the id column\n# submission['id'] = sub_1[['id']]\n'''","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_2[['id', 'home', 'away', 'draw']].head()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Conclusion\n**Good luck!**\n\nThe best accuracy of the validation set was 0.5015 so far, it is pretty low. You won't make money using this model.\n\nA huge LSTM makes worse predictions than a small LSTM. Need to work on this!\n\nReport any error that you will probably find.","metadata":{"_uuid":"002cd78f-9689-47ca-a8fe-2e28eba99b1d","_cell_guid":"4a755058-46c1-4ab7-9693-2381814c1bc0","trusted":true}}]}