{"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":"import os\nimport sys\nsys.path.append('/kaggle/input/timm-0-6-9/pytorch-image-models-master')\nimport glob\nimport numpy as np\nimport pandas as pd\nimport random\nimport math\nimport gc\nimport cv2\nfrom tqdm import tqdm\nimport time\nfrom functools import lru_cache\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda.amp import autocast, GradScaler\nimport timm\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import matthews_corrcoef","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2023-02-20T05:09:26.198889Z","iopub.status.busy":"2023-02-20T05:09:26.19797Z","iopub.status.idle":"2023-02-20T05:09:32.046217Z","shell.execute_reply":"2023-02-20T05:09:32.045115Z"},"papermill":{"duration":5.858625,"end_time":"2023-02-20T05:09:32.048949","exception":false,"start_time":"2023-02-20T05:09:26.190324","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CFG = {\n    'seed': 42,\n    'model': 'resnet50',\n    'img_size': 256,\n    'epochs': 10,\n    'train_bs': 100, \n    'valid_bs': 64,\n    'lr': 1e-3, \n    'weight_decay': 1e-6,\n    'num_workers': 2\n}","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:09:32.058965Z","iopub.status.busy":"2023-02-20T05:09:32.058021Z","iopub.status.idle":"2023-02-20T05:09:32.063419Z","shell.execute_reply":"2023-02-20T05:09:32.062502Z"},"papermill":{"duration":0.01224,"end_time":"2023-02-20T05:09:32.065442","exception":false,"start_time":"2023-02-20T05:09:32.053202","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n\nseed_everything(CFG['seed'])\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:09:32.074428Z","iopub.status.busy":"2023-02-20T05:09:32.074138Z","iopub.status.idle":"2023-02-20T05:09:32.142878Z","shell.execute_reply":"2023-02-20T05:09:32.141951Z"},"papermill":{"duration":0.076013,"end_time":"2023-02-20T05:09:32.145311","exception":false,"start_time":"2023-02-20T05:09:32.069298","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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\n\nlabels = expand_contact_id(pd.read_csv(\"/kaggle/input/nfl-player-contact-detection/sample_submission.csv\"))\n\ntest_tracking = pd.read_csv(\"/kaggle/input/nfl-player-contact-detection/test_player_tracking.csv\")\n\ntest_helmets = pd.read_csv(\"/kaggle/input/nfl-player-contact-detection/test_baseline_helmets.csv\")\n\ntest_video_metadata = pd.read_csv(\"/kaggle/input/nfl-player-contact-detection/test_video_metadata.csv\")","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:09:32.154851Z","iopub.status.busy":"2023-02-20T05:09:32.154201Z","iopub.status.idle":"2023-02-20T05:09:32.880771Z","shell.execute_reply":"2023-02-20T05:09:32.87975Z"},"papermill":{"duration":0.734132,"end_time":"2023-02-20T05:09:32.88358","exception":false,"start_time":"2023-02-20T05:09:32.149448","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir -p ../work/frames\n\nfor video in tqdm(test_helmets.video.unique()):\n    if 'Endzone2' not in video:\n        !ffmpeg -i /kaggle/input/nfl-player-contact-detection/test/{video} -q:v 2 -f image2 /kaggle/work/frames/{video}_%04d.jpg -hide_banner -loglevel error","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:09:32.89326Z","iopub.status.busy":"2023-02-20T05:09:32.892933Z","iopub.status.idle":"2023-02-20T05:10:20.092235Z","shell.execute_reply":"2023-02-20T05:10:20.090712Z"},"papermill":{"duration":47.207668,"end_time":"2023-02-20T05:10:20.095643","exception":false,"start_time":"2023-02-20T05:09:32.887975","status":"completed"},"tags":[]},"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        \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        \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\n\n\nuse_cols = [\n    'x_position', 'y_position', 'speed', 'distance',\n    'direction', 'orientation', 'acceleration', 'sa'\n]\n\ntest, feature_cols = create_features(labels, test_tracking, use_cols=use_cols)\ntest","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.106247Z","iopub.status.busy":"2023-02-20T05:10:20.105892Z","iopub.status.idle":"2023-02-20T05:10:20.389714Z","shell.execute_reply":"2023-02-20T05:10:20.388656Z"},"papermill":{"duration":0.291978,"end_time":"2023-02-20T05:10:20.392027","exception":false,"start_time":"2023-02-20T05:10:20.100049","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filtered = test.query('not distance>2').reset_index(drop=True)\ntest_filtered['frame'] = (test_filtered['step']/10*59.94+5*59.94).astype('int')+1\ntest_filtered","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.403344Z","iopub.status.busy":"2023-02-20T05:10:20.402991Z","iopub.status.idle":"2023-02-20T05:10:20.452232Z","shell.execute_reply":"2023-02-20T05:10:20.450983Z"},"papermill":{"duration":0.058132,"end_time":"2023-02-20T05:10:20.455318","exception":false,"start_time":"2023-02-20T05:10:20.397186","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del test, labels, test_tracking\ngc.collect()","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.467655Z","iopub.status.busy":"2023-02-20T05:10:20.467337Z","iopub.status.idle":"2023-02-20T05:10:20.652579Z","shell.execute_reply":"2023-02-20T05:10:20.651592Z"},"papermill":{"duration":0.193898,"end_time":"2023-02-20T05:10:20.654706","exception":false,"start_time":"2023-02-20T05:10:20.460808","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_aug = A.Compose([\n    A.HorizontalFlip(p=0.5),\n    A.ShiftScaleRotate(p=0.5),\n    A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=0.5),\n    A.Normalize(mean=[0.], std=[1.]),\n    ToTensorV2()\n])\n\nvalid_aug = A.Compose([\n    A.Normalize(mean=[0.], std=[1.]),\n    ToTensorV2()\n])","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.666702Z","iopub.status.busy":"2023-02-20T05:10:20.666003Z","iopub.status.idle":"2023-02-20T05:10:20.672866Z","shell.execute_reply":"2023-02-20T05:10:20.672004Z"},"papermill":{"duration":0.014818,"end_time":"2023-02-20T05:10:20.674837","exception":false,"start_time":"2023-02-20T05:10:20.660019","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"video2helmets = {}\ntest_helmets_new = test_helmets.set_index('video')\nfor video in tqdm(test_helmets.video.unique()):\n    video2helmets[video] = test_helmets_new.loc[video].reset_index(drop=True)\n    \ndel test_helmets, test_helmets_new\ngc.collect()","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.68617Z","iopub.status.busy":"2023-02-20T05:10:20.68589Z","iopub.status.idle":"2023-02-20T05:10:20.871614Z","shell.execute_reply":"2023-02-20T05:10:20.870165Z"},"papermill":{"duration":0.193776,"end_time":"2023-02-20T05:10:20.87369","exception":false,"start_time":"2023-02-20T05:10:20.679914","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"video2frames = {}\n\nfor game_play in tqdm(test_video_metadata.game_play.unique()):\n    for view in ['Endzone', 'Sideline']:\n        video = game_play + f'_{view}.mp4'\n        video2frames[video] = max(list(map(lambda x:int(x.split('_')[-1].split('.')[0]), \\\n                                           glob.glob(f'/kaggle/work/frames/{video}*'))))","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.885959Z","iopub.status.busy":"2023-02-20T05:10:20.885667Z","iopub.status.idle":"2023-02-20T05:10:20.925402Z","shell.execute_reply":"2023-02-20T05:10:20.924317Z"},"papermill":{"duration":0.049781,"end_time":"2023-02-20T05:10:20.929163","exception":false,"start_time":"2023-02-20T05:10:20.879382","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MyDataset(Dataset):\n    def __init__(self, df, aug=valid_aug, mode='train'):\n        self.df = df\n        self.frame = df.frame.values\n        self.feature = df[feature_cols].fillna(-1).values\n        self.players = df[['nfl_player_id_1','nfl_player_id_2']].values\n        self.game_play = df.game_play.values\n        self.aug = aug\n        self.mode = mode\n        \n    def __len__(self):\n        return len(self.df)\n    \n    # @lru_cache(1024)\n    # def read_img(self, path):\n    #     return cv2.imread(path, 0)\n   \n    def __getitem__(self, idx):   \n        window = 24\n        frame = self.frame[idx]\n        \n        if self.mode == 'train':\n            frame = frame + random.randint(-6, 6)\n\n        players = []\n        for p in self.players[idx]:\n            if p == 'G':\n                players.append(p)\n            else:\n                players.append(int(p))\n        \n        imgs = []\n        for view in ['Endzone', 'Sideline']:\n            video = self.game_play[idx] + f'_{view}.mp4'\n\n            tmp = video2helmets[video]\n            tmp = tmp.query('@frame-@window<=frame<=@frame+@window')\n            tmp = tmp[tmp.nfl_player_id.isin(players)]#.sort_values(['nfl_player_id', 'frame'])\n            tmp_frames = tmp.frame.values\n            tmp = tmp.groupby('frame')[['left','width','top','height']].mean()\n#0.002s\n\n            bboxes = []\n            for f in range(frame-window, frame+window+1, 1):\n                if f in tmp_frames:\n                    x, w, y, h = tmp.loc[f][['left','width','top','height']]\n                    bboxes.append([x, w, y, h])\n                else:\n                    bboxes.append([np.nan, np.nan, np.nan, np.nan])\n            bboxes = pd.DataFrame(bboxes).interpolate(limit_direction='both').values\n            bboxes = bboxes[::4]\n\n            if bboxes.sum() > 0:\n                flag = 1\n            else:\n                flag = 0\n#0.03s\n                    \n            for i, f in enumerate(range(frame-window, frame+window+1, 4)):\n                img_new = np.zeros((256, 256), dtype=np.float32)\n\n                if flag == 1 and f <= video2frames[video]:\n                    img = cv2.imread(f'/kaggle/work/frames/{video}_{f:04d}.jpg', 0)\n\n                    x, w, y, h = bboxes[i]\n\n                    img = img[int(y+h/2)-128:int(y+h/2)+128,int(x+w/2)-128:int(x+w/2)+128].copy()\n                    img_new[:img.shape[0], :img.shape[1]] = img\n                    \n                imgs.append(img_new)\n#0.06s\n                \n        feature = np.float32(self.feature[idx])\n\n        img = np.array(imgs).transpose(1, 2, 0)    \n        img = self.aug(image=img)[\"image\"]\n        label = np.float32(self.df.contact.values[idx])\n\n        return img, feature, label","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.941988Z","iopub.status.busy":"2023-02-20T05:10:20.941695Z","iopub.status.idle":"2023-02-20T05:10:20.957715Z","shell.execute_reply":"2023-02-20T05:10:20.956661Z"},"papermill":{"duration":0.025258,"end_time":"2023-02-20T05:10:20.960099","exception":false,"start_time":"2023-02-20T05:10:20.934841","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img, feature, label = MyDataset(test_filtered, valid_aug, 'test')[0]\nplt.imshow(img.permute(1,2,0)[:,:,7])\nplt.show()\nimg.shape, feature, label","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:20.97242Z","iopub.status.busy":"2023-02-20T05:10:20.972109Z","iopub.status.idle":"2023-02-20T05:10:21.405133Z","shell.execute_reply":"2023-02-20T05:10:21.404259Z"},"papermill":{"duration":0.442583,"end_time":"2023-02-20T05:10:21.408145","exception":false,"start_time":"2023-02-20T05:10:20.965562","status":"completed"},"tags":[]},"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(CFG['model'], 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, 64),\n            # nn.LayerNorm(64),\n            # nn.ReLU(),\n            # nn.Dropout(0.2)\n        )\n        self.fc = nn.Linear(64+500*2, 1)\n\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 = self.fc(torch.cat([img, feature], dim=1))\n        return y","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:21.42345Z","iopub.status.busy":"2023-02-20T05:10:21.423097Z","iopub.status.idle":"2023-02-20T05:10:21.430962Z","shell.execute_reply":"2023-02-20T05:10:21.429999Z"},"papermill":{"duration":0.017982,"end_time":"2023-02-20T05:10:21.433072","exception":false,"start_time":"2023-02-20T05:10:21.41509","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set = MyDataset(test_filtered, valid_aug, 'test')\ntest_loader = DataLoader(test_set, batch_size=CFG['valid_bs'], shuffle=False, num_workers=CFG['num_workers'], pin_memory=True)\n\nmodel = Model().to(device)\nmodel.load_state_dict(torch.load('/kaggle/input/nfl-exp1/resnet50_fold0.pt'))\n\nmodel.eval()\n    \ny_pred = []\nwith torch.no_grad():\n    tk = tqdm(test_loader, total=len(test_loader))\n    for step, batch in enumerate(tk):\n        img, feature, label = [x.to(device) for x in batch]\n        output = model(img.flip(-1), feature).squeeze(-1)\n\n        y_pred.extend(output.sigmoid().cpu().numpy())\n\ny_pred = np.array(y_pred)","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:10:21.447916Z","iopub.status.busy":"2023-02-20T05:10:21.447606Z","iopub.status.idle":"2023-02-20T05:27:03.972372Z","shell.execute_reply":"2023-02-20T05:27:03.970125Z"},"papermill":{"duration":1002.534542,"end_time":"2023-02-20T05:27:03.974497","exception":false,"start_time":"2023-02-20T05:10:21.439955","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"th = 0.29\n\ntest_filtered['contact'] = (y_pred >= th).astype('int')\n\nsub = pd.read_csv('/kaggle/input/nfl-player-contact-detection/sample_submission.csv')\n\nsub = sub.drop(\"contact\", axis=1).merge(test_filtered[['contact_id', 'contact']], how='left', on='contact_id')\nsub['contact'] = sub['contact'].fillna(0).astype('int')\n\nsub[[\"contact_id\", \"contact\"]].to_csv(\"submission.csv\", index=False)\n\nsub.head()","metadata":{"execution":{"iopub.execute_input":"2023-02-20T05:27:04.001336Z","iopub.status.busy":"2023-02-20T05:27:03.999871Z","iopub.status.idle":"2023-02-20T05:27:04.13869Z","shell.execute_reply":"2023-02-20T05:27:04.13777Z"},"papermill":{"duration":0.154257,"end_time":"2023-02-20T05:27:04.140869","exception":false,"start_time":"2023-02-20T05:27:03.986612","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]}]}