{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport sys\nsys.path.append('/kaggle/input/timmmaster')\nimport timm","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:37:44.52585Z","iopub.execute_input":"2023-02-11T13:37:44.526352Z","iopub.status.idle":"2023-02-11T13:37:47.845017Z","shell.execute_reply.started":"2023-02-11T13:37:44.526248Z","shell.execute_reply":"2023-02-11T13:37:47.843666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"folder = \"/kaggle/input/nfl-player-contact-detection/\"\n\ndef expand_contact_id(df):\n    \"\"\"\n    Splits out contact_id into seperate columns.\n    \"\"\"\n    df[\"game_play\"] = df[\"contact_id\"].str[:12]\n    df[\"step\"] = df[\"contact_id\"].str.split(\"_\").str[-3].astype(\"int\")\n    df[\"nfl_player_id_1\"] = df[\"contact_id\"].str.split(\"_\").str[-2]\n    df[\"nfl_player_id_2\"] = df[\"contact_id\"].str.split(\"_\").str[-1]\n    return df","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:37:47.850232Z","iopub.execute_input":"2023-02-11T13:37:47.850659Z","iopub.status.idle":"2023-02-11T13:37:47.858759Z","shell.execute_reply.started":"2023-02-11T13:37:47.85062Z","shell.execute_reply":"2023-02-11T13:37:47.857556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = expand_contact_id(pd.read_csv(folder+\"train_labels.csv\")[[\"contact_id\",\"contact\"]])\ntrain_tracking = pd.read_csv(folder+\"train_player_tracking.csv\")\ntrain_helmets = pd.read_csv(folder+\"train_baseline_helmets.csv\")\ntrain_video_metadata = pd.read_csv(folder+\"train_video_metadata.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:38:03.34527Z","iopub.execute_input":"2023-02-11T13:38:03.34657Z","iopub.status.idle":"2023-02-11T13:39:04.210597Z","shell.execute_reply.started":"2023-02-11T13:38:03.346522Z","shell.execute_reply":"2023-02-11T13:39:04.209399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_features(df, tr_tracking, merge_col=\"step\", use_cols=[\"x_position\", \"y_position\"]):\n    output_cols = []\n    df_combo = (\n        df.astype({\"nfl_player_id_1\": \"str\"})\n        .merge(\n            tr_tracking.astype({\"nfl_player_id\": \"str\"})[\n                [\"game_play\", merge_col, \"nfl_player_id\",] + use_cols\n            ],\n            left_on=[\"game_play\", merge_col, \"nfl_player_id_1\"],\n            right_on=[\"game_play\", merge_col, \"nfl_player_id\"],\n            how=\"left\",\n        )\n        .rename(columns={c: c+\"_1\" for c in use_cols})\n        .drop(\"nfl_player_id\", axis=1)\n        .merge(\n            tr_tracking.astype({\"nfl_player_id\": \"str\"})[\n                [\"game_play\", merge_col, \"nfl_player_id\"] + use_cols\n            ],\n            left_on=[\"game_play\", merge_col, \"nfl_player_id_2\"],\n            right_on=[\"game_play\", merge_col, \"nfl_player_id\"],\n            how=\"left\",\n        )\n        .drop(\"nfl_player_id\", axis=1)\n        .rename(columns={c: c+\"_2\" for c in use_cols})\n        .sort_values([\"game_play\", merge_col, \"nfl_player_id_1\", \"nfl_player_id_2\"])\n        .reset_index(drop=True)\n    )\n    output_cols += [c+\"_1\" for c in use_cols]\n    output_cols += [c+\"_2\" for c in use_cols]\n    \n    if (\"x_position\" in use_cols) & (\"y_position\" in use_cols):\n        index = df_combo['x_position_2'].notnull()\n        distance_arr = np.full(len(index), np.nan)\n        tmp_distance_arr = np.sqrt(\n            np.square(df_combo.loc[index, \"x_position_1\"] - df_combo.loc[index, \"x_position_2\"])\n            + np.square(df_combo.loc[index, \"y_position_1\"]- df_combo.loc[index, \"y_position_2\"])\n        )\n        distance_arr[index] = tmp_distance_arr\n        df_combo['distance'] = distance_arr\n        output_cols += [\"distance\"]\n        \n    df_combo['G_flug'] = (df_combo['nfl_player_id_2']==\"G\")\n    output_cols += [\"G_flug\"]\n    return df_combo, output_cols\nuse_cols = [\n    'x_position', 'y_position', 'speed', 'distance',\n    'direction', 'orientation', 'acceleration', 'sa'\n]\n\ntreshold_dist = 2\ntrain, feature_cols = create_features(train_labels, train_tracking, use_cols=use_cols)\ntrain_filtered = train.query('distance<@treshold_dist').reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:39:04.212727Z","iopub.execute_input":"2023-02-11T13:39:04.213986Z","iopub.status.idle":"2023-02-11T13:39:32.348575Z","shell.execute_reply.started":"2023-02-11T13:39:04.213904Z","shell.execute_reply":"2023-02-11T13:39:32.347151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import GroupKFold\nfrom sklearn import preprocessing\n\nle = preprocessing.LabelEncoder()\ngroup = le.fit_transform(train_filtered[\"game_play\"])\n\ngroup_kfold = GroupKFold(n_splits=5)\n\nfor fold, (train_index, val_index) in enumerate(group_kfold.split(train_filtered, groups=group)):\n    \n\n    pass","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:39:32.350521Z","iopub.execute_input":"2023-02-11T13:39:32.350937Z","iopub.status.idle":"2023-02-11T13:39:32.943211Z","shell.execute_reply.started":"2023-02-11T13:39:32.350884Z","shell.execute_reply":"2023-02-11T13:39:32.941825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch import nn","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:39:39.56601Z","iopub.execute_input":"2023-02-11T13:39:39.566471Z","iopub.status.idle":"2023-02-11T13:39:39.57164Z","shell.execute_reply.started":"2023-02-11T13:39:39.566432Z","shell.execute_reply":"2023-02-11T13:39:39.570354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Model(nn.Module):\n    def __init__(self):\n        super(Model, self).__init__()\n        self.backbone = timm.create_model('efficientnet_b4', pretrained=False, num_classes=500, in_chans=13)\n        self.mlp = nn.Sequential(\n            nn.Linear(18, 64),\n            nn.LayerNorm(64),\n            nn.ReLU(),\n            nn.Dropout(0.2),\n            nn.Linear(64, 32),\n            nn.LayerNorm(32),\n        )\n        self.fc = nn.Linear(32+500*2, 1)\n    def forward(self, img, feature):\n        b, c, h, w = img.shape\n        img = img.reshape(b*2, c//2, h, w)\n        img = self.backbone(img).reshape(b, -1)\n        feature = self.mlp(feature)\n        y = nn.Sigmoid()(self.fc(torch.cat([img, feature], dim=1)))\n        return y\n","metadata":{"execution":{"iopub.status.busy":"2023-02-11T13:40:00.245417Z","iopub.execute_input":"2023-02-11T13:40:00.245832Z","iopub.status.idle":"2023-02-11T13:40:00.255887Z","shell.execute_reply.started":"2023-02-11T13:40:00.245799Z","shell.execute_reply":"2023-02-11T13:40:00.254975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model()\nPATH = \"/kaggle/input/nflefficientnet-b4/efficientnet_b4_fold_0.pt\"\nmodel.load_state_dict(torch.load(PATH,map_location=\"cpu\"))\nmodel(torch.rand(5,26,256,256),torch.rand(5,18))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}