{"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":"# 🤝 Intro ","metadata":{}},{"cell_type":"markdown","source":"Rocket League is fun.","metadata":{}},{"cell_type":"markdown","source":"![Rocket League](https://media2.giphy.com/media/xT0xepBLaRaduNgkne/giphy.gif?cid=ecf05e47c5ru2uhkoa15ekp0l8fm1lz43bwtyehz0tywlwum&rid=giphy.gif&ct=g)","metadata":{}},{"cell_type":"markdown","source":"Let's have some fun predicting the probability of a team scoring, within 10 seconds.","metadata":{}},{"cell_type":"markdown","source":"# 🚚 Import","metadata":{}},{"cell_type":"markdown","source":"## Packages","metadata":{}},{"cell_type":"code","source":"import numpy as np  # linear algebra\nimport pandas as pd  # data manipulation\nimport os  # file navigation\nimport gc  # garbage collection\n\n# visualization\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly import subplots\n\nfrom sklearn.model_selection import cross_validate  # k-fold Cross Validation\nfrom sklearn.preprocessing import LabelEncoder  # output binary encoding\n\nfrom xgboost import XGBClassifier  # Gradient Boosted Tree (XGBoost)\n\nfrom tensorflow.config import list_physical_devices  # check if GPU is available","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-10-05T08:38:16.365039Z","iopub.execute_input":"2022-10-05T08:38:16.365769Z","iopub.status.idle":"2022-10-05T08:38:23.888641Z","shell.execute_reply.started":"2022-10-05T08:38:16.365732Z","shell.execute_reply":"2022-10-05T08:38:23.887595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Config","metadata":{}},{"cell_type":"code","source":"# training and cross validation\nGPU = list_physical_devices('GPU') != []\nN_ESTIMATORS = 2000\nMAX_DEPTH = 8\nLEARNING_RATE = 0.01\nFOLDS = 5\n\n# data loading\nDEBUG = False\nSAMPLE = 0.2\nSEED = 42","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:23.890853Z","iopub.execute_input":"2022-10-05T08:38:23.891733Z","iopub.status.idle":"2022-10-05T08:38:23.975868Z","shell.execute_reply.started":"2022-10-05T08:38:23.891693Z","shell.execute_reply":"2022-10-05T08:38:23.974682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataset","metadata":{}},{"cell_type":"markdown","source":"Because of memory limitations, we can't use all of the data from the 10 train .csv files.  \nInstead, we'll get a random sample of each file (for now I'm experimenting with 20-33% sample size), and combine these samples into a unique training dataset.","metadata":{}},{"cell_type":"code","source":"for dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-10-05T08:38:23.977315Z","iopub.execute_input":"2022-10-05T08:38:23.978490Z","iopub.status.idle":"2022-10-05T08:38:23.986987Z","shell.execute_reply.started":"2022-10-05T08:38:23.978451Z","shell.execute_reply":"2022-10-05T08:38:23.985889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ncol_dtypes = {\n    'game_num': 'int8', 'event_id': 'int8', 'event_time': 'float16',\n    'ball_pos_x': 'float16', 'ball_pos_y': 'float16', 'ball_pos_z': 'float16',\n    'ball_vel_x': 'float16', 'ball_vel_y': 'float16', 'ball_vel_z': 'float16',\n    'p0_pos_x': 'float16', 'p0_pos_y': 'float16', 'p0_pos_z': 'float16',\n    'p0_vel_x': 'float16', 'p0_vel_y': 'float16', 'p0_vel_z': 'float16',\n    'p0_boost': 'float16', 'p1_pos_x': 'float16', 'p1_pos_y': 'float16',\n    'p1_pos_z': 'float16', 'p1_vel_x': 'float16', 'p1_vel_y': 'float16',\n    'p1_vel_z': 'float16', 'p1_boost': 'float16', 'p2_pos_x': 'float16',\n    'p2_pos_y': 'float16', 'p2_pos_z': 'float16', 'p2_vel_x': 'float16',\n    'p2_vel_y': 'float16', 'p2_vel_z': 'float16', 'p2_boost': 'float16',\n    'p3_pos_x': 'float16', 'p3_pos_y': 'float16', 'p3_pos_z': 'float16',\n    'p3_vel_x': 'float16', 'p3_vel_y': 'float16', 'p3_vel_z': 'float16',\n    'p3_boost': 'float16', 'p4_pos_x': 'float16', 'p4_pos_y': 'float16',\n    'p4_pos_z': 'float16', 'p4_vel_x': 'float16', 'p4_vel_y': 'float16',\n    'p4_vel_z': 'float16', 'p4_boost': 'float16', 'p5_pos_x': 'float16',\n    'p5_pos_y': 'float16', 'p5_pos_z': 'float16', 'p5_vel_x': 'float16',\n    'p5_vel_y': 'float16', 'p5_vel_z': 'float16', 'p5_boost': 'float16',\n    'boost0_timer': 'float16', 'boost1_timer': 'float16', 'boost2_timer': 'float16',\n    'boost3_timer': 'float16', 'boost4_timer': 'float16', 'boost5_timer': 'float16',\n    'player_scoring_next': 'O', 'team_scoring_next': 'O', 'team_A_scoring_within_10sec': 'O',\n    'team_B_scoring_within_10sec': 'O'\n}\ncols = list(col_dtypes.keys())\n\npath_to_data = '../input/tabular-playground-series-oct-2022'\ndf = pd.DataFrame({}, columns=cols)\nfor i in range(10):\n    df_tmp = pd.read_csv(f'{path_to_data}/train_{i}.csv', dtype=col_dtypes)\n    if SAMPLE < 1:\n        df_tmp = df_tmp.sample(frac=SAMPLE, random_state=SEED)\n        \n    df = pd.concat([df, df_tmp])\n    del df_tmp\n    gc.collect()\n    if DEBUG:\n        break","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:23.990115Z","iopub.execute_input":"2022-10-05T08:38:23.990476Z","iopub.status.idle":"2022-10-05T08:38:51.086237Z","shell.execute_reply.started":"2022-10-05T08:38:23.990441Z","shell.execute_reply":"2022-10-05T08:38:51.085165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.087806Z","iopub.execute_input":"2022-10-05T08:38:51.088470Z","iopub.status.idle":"2022-10-05T08:38:51.227989Z","shell.execute_reply.started":"2022-10-05T08:38:51.088429Z","shell.execute_reply":"2022-10-05T08:38:51.226919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 👀 Quick EDA","metadata":{}},{"cell_type":"code","source":"input_cols = [\n    'ball_pos_x', 'ball_pos_y', 'ball_pos_z', 'ball_vel_x', 'ball_vel_y', 'ball_vel_z', \n    'p0_pos_x', 'p0_pos_y', 'p0_pos_z', 'p0_vel_x', 'p0_vel_y', 'p0_vel_z', \n    'p1_pos_x', 'p1_pos_y', 'p1_pos_z', 'p1_vel_x', 'p1_vel_y', 'p1_vel_z',\n    'p2_pos_x', 'p2_pos_y', 'p2_pos_z', 'p2_vel_x', 'p2_vel_y', 'p2_vel_z',\n    'p3_pos_x', 'p3_pos_y', 'p3_pos_z', 'p3_vel_x', 'p3_vel_y', 'p3_vel_z',\n    'p4_pos_x', 'p4_pos_y', 'p4_pos_z', 'p4_vel_x', 'p4_vel_y', 'p4_vel_z',\n    'p5_pos_x', 'p5_pos_y', 'p5_pos_z', 'p5_vel_x', 'p5_vel_y', 'p5_vel_z',\n    'p0_boost', 'p1_boost',  'p2_boost', 'p3_boost', 'p4_boost', 'p5_boost',\n    'boost0_timer', 'boost1_timer', 'boost2_timer', 'boost3_timer', 'boost4_timer', 'boost5_timer'\n]","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.229515Z","iopub.execute_input":"2022-10-05T08:38:51.230268Z","iopub.status.idle":"2022-10-05T08:38:51.237886Z","shell.execute_reply.started":"2022-10-05T08:38:51.230228Z","shell.execute_reply":"2022-10-05T08:38:51.236850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output_cols = ['team_A_scoring_within_10sec', 'team_B_scoring_within_10sec']","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.239394Z","iopub.execute_input":"2022-10-05T08:38:51.239865Z","iopub.status.idle":"2022-10-05T08:38:51.252559Z","shell.execute_reply.started":"2022-10-05T08:38:51.239826Z","shell.execute_reply":"2022-10-05T08:38:51.251554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Input Variables","metadata":{}},{"cell_type":"code","source":"def int_to_grid_coord(k, n):\n    return (k // n) + 1, (k % n) + 1","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.253954Z","iopub.execute_input":"2022-10-05T08:38:51.254467Z","iopub.status.idle":"2022-10-05T08:38:51.263336Z","shell.execute_reply.started":"2022-10-05T08:38:51.254431Z","shell.execute_reply":"2022-10-05T08:38:51.262293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_distributions(df, row_count, col_count, title, height):\n    features = df.columns\n    fig = subplots.make_subplots(\n        rows=row_count, cols=col_count,\n        subplot_titles=features\n    )\n\n    for k, col in enumerate(features):\n        i, j = int_to_grid_coord(k, col_count)\n\n        fig.add_trace(\n            go.Histogram(\n                x=df[col].astype('float32'),\n                name=col\n            ),\n            row=i, col=j\n        )\n\n    fig.update_layout(\n        title=title,\n        height=row_count * height,\n        showlegend=False\n    )\n\n    return fig","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.264656Z","iopub.execute_input":"2022-10-05T08:38:51.265389Z","iopub.status.idle":"2022-10-05T08:38:51.274015Z","shell.execute_reply.started":"2022-10-05T08:38:51.265336Z","shell.execute_reply":"2022-10-05T08:38:51.273071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_distributions(df[input_cols].sample(frac=0.0005), 9, 6, \"Input Variables Distributions\", 300)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:51.279210Z","iopub.execute_input":"2022-10-05T08:38:51.279702Z","iopub.status.idle":"2022-10-05T08:38:52.305764Z","shell.execute_reply.started":"2022-10-05T08:38:51.279675Z","shell.execute_reply":"2022-10-05T08:38:52.304752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Output Variables","metadata":{}},{"cell_type":"code","source":"plot_distributions(df[output_cols].sample(frac=0.0005), 1, 2, \"Output Variables Distributions\", height=600)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:52.306782Z","iopub.execute_input":"2022-10-05T08:38:52.307119Z","iopub.status.idle":"2022-10-05T08:38:52.360955Z","shell.execute_reply.started":"2022-10-05T08:38:52.307083Z","shell.execute_reply":"2022-10-05T08:38:52.359990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ⚙️ Feature Engineering","metadata":{}},{"cell_type":"markdown","source":"Shoutout [this post by samuelcortinhas](https://www.kaggle.com/competitions/tabular-playground-series-oct-2022/discussion/356852) for the idea.","metadata":{}},{"cell_type":"markdown","source":"Let's derive 2 new features:\n* For each player (and the ball) let's get their velocity's magnitude.\n* For each player, let's get their distance from the ball.","metadata":{}},{"cell_type":"markdown","source":"## Euclidian Norm","metadata":{}},{"cell_type":"markdown","source":"For these 2 new features, we'll need to get the 3D euclidian norm of a vector:\n$$ \\| \\overrightarrow{v} \\| = \\sqrt{x^2 + y^2 + z^2} $$\nWe'll use numpy's linalg.norm() method for that.","metadata":{}},{"cell_type":"code","source":"def euclidian_norm(x):\n    return np.linalg.norm(x, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:52.362455Z","iopub.execute_input":"2022-10-05T08:38:52.362902Z","iopub.status.idle":"2022-10-05T08:38:52.368196Z","shell.execute_reply.started":"2022-10-05T08:38:52.362865Z","shell.execute_reply":"2022-10-05T08:38:52.367128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# let's group the x, y and z variables by player and ball categories\n# this simplifies the code for the euclidian norm calculation\nvel_groups = {\n    f\"{el}_vel\": [f'{el}_vel_x', f'{el}_vel_y', f'{el}_vel_z']\n    for el in ['ball'] + [f'p{i}' for i in range(6)]\n}\npos_groups = {\n    f\"{el}_pos\": [f'{el}_pos_x', f'{el}_pos_y', f'{el}_pos_z']\n    for el in ['ball'] + [f'p{i}' for i in range(6)]\n}\npos_groups","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:52.370027Z","iopub.execute_input":"2022-10-05T08:38:52.370398Z","iopub.status.idle":"2022-10-05T08:38:52.381247Z","shell.execute_reply.started":"2022-10-05T08:38:52.370340Z","shell.execute_reply":"2022-10-05T08:38:52.380306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# velocity magnitude\nfor col, vec in vel_groups.items():\n    df[col] = euclidian_norm(df[vec])","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:52.382903Z","iopub.execute_input":"2022-10-05T08:38:52.383267Z","iopub.status.idle":"2022-10-05T08:38:52.923456Z","shell.execute_reply.started":"2022-10-05T08:38:52.383229Z","shell.execute_reply":"2022-10-05T08:38:52.922461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# distance from ball\nfor col, vec in pos_groups.items():\n    df[col + \"_ball_dist\"] = euclidian_norm(df[vec].values - df[pos_groups[\"ball_pos\"]].values)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:52.924983Z","iopub.execute_input":"2022-10-05T08:38:52.925863Z","iopub.status.idle":"2022-10-05T08:38:53.511186Z","shell.execute_reply.started":"2022-10-05T08:38:52.925823Z","shell.execute_reply":"2022-10-05T08:38:53.510163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🧹 Cleaning","metadata":{}},{"cell_type":"markdown","source":"We drop the columns below because they should not influence the results.  \ngame_num, event_id and event_time are irrelevant.  \nplayer_scoring_next and team_scoring next are a form of data leakage, as in they're synonymous with the output variable.  \nball_pos_ball_dist is always 0, the distance between the ball and itself.","metadata":{}},{"cell_type":"markdown","source":"## Dropping columns","metadata":{}},{"cell_type":"code","source":"cols_to_drop = [\n    'game_num', 'event_id', 'event_time', 'player_scoring_next', 'team_scoring_next', 'ball_pos_ball_dist'\n]","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.512766Z","iopub.execute_input":"2022-10-05T08:38:53.513372Z","iopub.status.idle":"2022-10-05T08:38:53.518398Z","shell.execute_reply.started":"2022-10-05T08:38:53.513310Z","shell.execute_reply":"2022-10-05T08:38:53.517461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.drop(columns=cols_to_drop)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.519802Z","iopub.execute_input":"2022-10-05T08:38:53.520920Z","iopub.status.idle":"2022-10-05T08:38:53.611582Z","shell.execute_reply.started":"2022-10-05T08:38:53.520883Z","shell.execute_reply":"2022-10-05T08:38:53.610515Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.613202Z","iopub.execute_input":"2022-10-05T08:38:53.613584Z","iopub.status.idle":"2022-10-05T08:38:53.662747Z","shell.execute_reply.started":"2022-10-05T08:38:53.613546Z","shell.execute_reply":"2022-10-05T08:38:53.661635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dropping rows containing NaN","metadata":{}},{"cell_type":"code","source":"has_na = {}\nfor col in df.columns:\n    has_na[col] = df[col].isnull().values.any()\n\nprint(\"Columns that contain null values:\")\nfor col in has_na:\n    if has_na[col]:\n        print(col)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.664552Z","iopub.execute_input":"2022-10-05T08:38:53.664933Z","iopub.status.idle":"2022-10-05T08:38:53.771209Z","shell.execute_reply.started":"2022-10-05T08:38:53.664895Z","shell.execute_reply":"2022-10-05T08:38:53.770183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"null_p0_pos_x_count = df['p0_pos_x'].isna().sum()\nnull_p0_pos_x_perc = null_p0_pos_x_count / df.shape[0]\nprint(f\"Missing {null_p0_pos_x_count} values ({null_p0_pos_x_perc:.2%})\")","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.772955Z","iopub.execute_input":"2022-10-05T08:38:53.773538Z","iopub.status.idle":"2022-10-05T08:38:53.781633Z","shell.execute_reply.started":"2022-10-05T08:38:53.773492Z","shell.execute_reply":"2022-10-05T08:38:53.780467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"To keep things simple, let's just drop all null values.","metadata":{}},{"cell_type":"code","source":"df = df.dropna(axis=0)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:53.783418Z","iopub.execute_input":"2022-10-05T08:38:53.784117Z","iopub.status.idle":"2022-10-05T08:38:54.231437Z","shell.execute_reply.started":"2022-10-05T08:38:53.784080Z","shell.execute_reply":"2022-10-05T08:38:54.230395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"has_na = {}\nfor col in df.columns:\n    has_na[col] = df[col].isnull().values.any()\n\nprint(\"Columns that contain null values:\")\nfor col in has_na:\n    if has_na[col]:\n        print(col)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:54.235975Z","iopub.execute_input":"2022-10-05T08:38:54.238552Z","iopub.status.idle":"2022-10-05T08:38:54.398248Z","shell.execute_reply.started":"2022-10-05T08:38:54.238513Z","shell.execute_reply":"2022-10-05T08:38:54.395917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:54.399659Z","iopub.execute_input":"2022-10-05T08:38:54.400226Z","iopub.status.idle":"2022-10-05T08:38:54.475691Z","shell.execute_reply.started":"2022-10-05T08:38:54.400188Z","shell.execute_reply":"2022-10-05T08:38:54.474696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🚀 Model Training","metadata":{}},{"cell_type":"markdown","source":"We'll be predicting the probability of team A scoring and team B scoring with 2 separate models.","metadata":{}},{"cell_type":"markdown","source":"## Model A","metadata":{}},{"cell_type":"code","source":"# used to encode the binary classes\nle_a = LabelEncoder()","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:54.479751Z","iopub.execute_input":"2022-10-05T08:38:54.481865Z","iopub.status.idle":"2022-10-05T08:38:54.487917Z","shell.execute_reply.started":"2022-10-05T08:38:54.481825Z","shell.execute_reply":"2022-10-05T08:38:54.487050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_a = XGBClassifier(\n    n_estimators=N_ESTIMATORS,\n    max_depth=MAX_DEPTH,\n    learning_rate=LEARNING_RATE,\n    objective='binary:logistic',\n    tree_method='gpu_hist' if GPU else 'hist'\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:54.489273Z","iopub.execute_input":"2022-10-05T08:38:54.489832Z","iopub.status.idle":"2022-10-05T08:38:54.499044Z","shell.execute_reply.started":"2022-10-05T08:38:54.489797Z","shell.execute_reply":"2022-10-05T08:38:54.498184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv_a = cross_validate(\n    model_a, \n    X=df.drop(columns=['team_A_scoring_within_10sec', 'team_B_scoring_within_10sec']).values,\n    y=le_a.fit_transform(df['team_A_scoring_within_10sec'].values),\n    scoring=\"neg_log_loss\",\n    cv=FOLDS,\n    verbose=2,\n    return_estimator=True\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:38:54.500604Z","iopub.execute_input":"2022-10-05T08:38:54.502683Z","iopub.status.idle":"2022-10-05T08:39:26.785440Z","shell.execute_reply.started":"2022-10-05T08:38:54.501515Z","shell.execute_reply":"2022-10-05T08:39:26.784412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model B","metadata":{}},{"cell_type":"code","source":"# used to encode the binary classes\nle_b = LabelEncoder()","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:26.787158Z","iopub.execute_input":"2022-10-05T08:39:26.787866Z","iopub.status.idle":"2022-10-05T08:39:26.792849Z","shell.execute_reply.started":"2022-10-05T08:39:26.787828Z","shell.execute_reply":"2022-10-05T08:39:26.791792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_b = XGBClassifier(\n    n_estimators=N_ESTIMATORS,\n    max_depth=MAX_DEPTH,\n    learning_rate=LEARNING_RATE,\n    objective='binary:logistic',\n    tree_method='gpu_hist' if GPU else 'hist'\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:26.798698Z","iopub.execute_input":"2022-10-05T08:39:26.799057Z","iopub.status.idle":"2022-10-05T08:39:26.810395Z","shell.execute_reply.started":"2022-10-05T08:39:26.799020Z","shell.execute_reply":"2022-10-05T08:39:26.808800Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv_b = cross_validate(\n    model_b, \n    X=df.drop(columns=['team_A_scoring_within_10sec', 'team_B_scoring_within_10sec']).values,\n    y=le_b.fit_transform(df['team_B_scoring_within_10sec'].values),\n    scoring=\"neg_log_loss\",\n    cv=FOLDS,\n    verbose=2,\n    return_estimator=True\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:26.812086Z","iopub.execute_input":"2022-10-05T08:39:26.812504Z","iopub.status.idle":"2022-10-05T08:39:57.496484Z","shell.execute_reply.started":"2022-10-05T08:39:26.812432Z","shell.execute_reply":"2022-10-05T08:39:57.495422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ✔️ Model Evaluation","metadata":{}},{"cell_type":"markdown","source":"## Cross Validation Test Score","metadata":{}},{"cell_type":"markdown","source":"Let's visualize the log loss score on each of our folds, for both our models","metadata":{}},{"cell_type":"code","source":"df_cv_a = pd.DataFrame(\n    {\n        \"model\": \"Model A\",\n        \"fold\": list(range(FOLDS)),\n        \"test_log_loss\": - cv_a[\"test_score\"]\n    }\n)\ndf_cv_b = pd.DataFrame(\n    {\n        \"model\": \"Model B\",\n        \"fold\": list(range(FOLDS)),\n        \"test_log_loss\": - cv_b[\"test_score\"]\n    }\n)\ndf_cv = pd.concat([df_cv_a, df_cv_b])\n\ndel df_cv_a\ndel df_cv_b\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:57.498412Z","iopub.execute_input":"2022-10-05T08:39:57.499104Z","iopub.status.idle":"2022-10-05T08:39:57.704810Z","shell.execute_reply.started":"2022-10-05T08:39:57.499062Z","shell.execute_reply":"2022-10-05T08:39:57.703732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"px.bar(\n    df_cv, x='fold', y='test_log_loss', color='model', \n    barmode='group', title='Cross Validation Log Loss'\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:57.706447Z","iopub.execute_input":"2022-10-05T08:39:57.706832Z","iopub.status.idle":"2022-10-05T08:39:58.348224Z","shell.execute_reply.started":"2022-10-05T08:39:57.706795Z","shell.execute_reply":"2022-10-05T08:39:58.347264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 💌 Submission","metadata":{}},{"cell_type":"code","source":"df_test = pd.read_csv('/kaggle/input/tabular-playground-series-oct-2022/test.csv')\ndf_test","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:39:58.349871Z","iopub.execute_input":"2022-10-05T08:39:58.350556Z","iopub.status.idle":"2022-10-05T08:40:07.167412Z","shell.execute_reply.started":"2022-10-05T08:39:58.350507Z","shell.execute_reply":"2022-10-05T08:40:07.166395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess(df):\n    # velocity magnitude\n    for col, vec in vel_groups.items():\n        df[col] = euclidian_norm(df[vec])\n    \n    # ball distance\n    for col, vec in pos_groups.items():\n        df[col + \"_ball_dist\"] = euclidian_norm(df[vec].values - df[pos_groups[\"ball_pos\"]].values)\n    \n    df = df.drop(columns=['ball_pos_ball_dist'])\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:40:07.169062Z","iopub.execute_input":"2022-10-05T08:40:07.169724Z","iopub.status.idle":"2022-10-05T08:40:07.177080Z","shell.execute_reply.started":"2022-10-05T08:40:07.169681Z","shell.execute_reply":"2022-10-05T08:40:07.176014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = preprocess(df_test)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:40:07.178725Z","iopub.execute_input":"2022-10-05T08:40:07.179161Z","iopub.status.idle":"2022-10-05T08:40:10.692180Z","shell.execute_reply.started":"2022-10-05T08:40:07.179124Z","shell.execute_reply":"2022-10-05T08:40:10.691126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n# take the mean of the predictions made by the k models gotten out of the k-fold cross validation\npred_a = np.zeros(df_test.shape[0])\nfor estimator in cv_a['estimator']:\n    pred_a += estimator.predict_proba(df_test.drop(columns=['id']).values)[:, 1]\n\npred_a /= FOLDS","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:40:10.693878Z","iopub.execute_input":"2022-10-05T08:40:10.694271Z","iopub.status.idle":"2022-10-05T08:40:37.937258Z","shell.execute_reply.started":"2022-10-05T08:40:10.694233Z","shell.execute_reply":"2022-10-05T08:40:37.936373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n# take the mean of the predictions made by the k models gotten out of the k-fold cross validation\npred_b = np.zeros(df_test.shape[0])\nfor estimator in cv_b['estimator']:\n    pred_b += estimator.predict_proba(df_test.drop(columns=['id']).values)[:, 1]\n\npred_b /= FOLDS","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:40:37.940630Z","iopub.execute_input":"2022-10-05T08:40:37.940919Z","iopub.status.idle":"2022-10-05T08:41:05.074000Z","shell.execute_reply.started":"2022-10-05T08:40:37.940891Z","shell.execute_reply":"2022-10-05T08:41:05.073061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission = pd.DataFrame(\n    {\n        \"id\": df_test['id'],\n        \"team_A_scoring_within_10sec\": pred_a,\n        \"team_B_scoring_within_10sec\": pred_b\n    }\n)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:41:05.077890Z","iopub.execute_input":"2022-10-05T08:41:05.079106Z","iopub.status.idle":"2022-10-05T08:41:05.087590Z","shell.execute_reply.started":"2022-10-05T08:41:05.079065Z","shell.execute_reply":"2022-10-05T08:41:05.086461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:41:05.090120Z","iopub.execute_input":"2022-10-05T08:41:05.090481Z","iopub.status.idle":"2022-10-05T08:41:05.107317Z","shell.execute_reply.started":"2022-10-05T08:41:05.090424Z","shell.execute_reply":"2022-10-05T08:41:05.106319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-05T08:41:05.110061Z","iopub.execute_input":"2022-10-05T08:41:05.110353Z","iopub.status.idle":"2022-10-05T08:41:07.257435Z","shell.execute_reply.started":"2022-10-05T08:41:05.110324Z","shell.execute_reply":"2022-10-05T08:41:07.256401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}