{"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":"# Notes","metadata":{"papermill":{"duration":0.04953,"end_time":"2021-02-16T15:59:39.560117","exception":false,"start_time":"2021-02-16T15:59:39.510587","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"In this kenel, I'm going to use a classical **ResneSt50** for bird identification.","metadata":{"papermill":{"duration":0.04754,"end_time":"2021-02-16T15:59:39.092567","exception":false,"start_time":"2021-02-16T15:59:39.045027","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"* The inference is based on these [resnest50 weights](https://www.kaggle.com/kneroma/kkiller-birdclef-models-public). Please, don't forget upvoting the dataset to make it more visible for others\n* The inference pipeline is optimized as much as I can in order to reduce execution time","metadata":{"papermill":{"duration":0.04461,"end_time":"2021-02-16T15:59:39.651121","exception":false,"start_time":"2021-02-16T15:59:39.606511","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"**If the only thing you wan't to change is `hyperparams`, please consider commenting instead of spamming with stupid forks !**","metadata":{}},{"cell_type":"markdown","source":"<h2><font color=\"blue\">If you find this work useful, please don't forget upvoting :)</font></h2>","metadata":{"papermill":{"duration":0.052753,"end_time":"2021-02-16T15:59:39.926669","exception":false,"start_time":"2021-02-16T15:59:39.873916","status":"completed"},"tags":[]}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!nvidia-smi","metadata":{"id":"ikMF-nQSdTbF","outputId":"041c6767-86ab-46e4-9b22-a4840121ecca","papermill":{"duration":1.301859,"end_time":"2021-02-16T15:59:41.363841","exception":false,"start_time":"2021-02-16T15:59:40.061982","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:39.504565Z","iopub.execute_input":"2021-06-01T16:21:39.504976Z","iopub.status.idle":"2021-06-01T16:21:40.171031Z","shell.execute_reply.started":"2021-06-01T16:21:39.504893Z","shell.execute_reply":"2021-06-01T16:21:40.169859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    import resnest\nexcept ModuleNotFoundError:\n    !pip install -q \"../input/resnest50-fast-package/resnest-0.0.6b20200701/resnest\"","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:40.172557Z","iopub.execute_input":"2021-06-01T16:21:40.172927Z","iopub.status.idle":"2021-06-01T16:21:40.181137Z","shell.execute_reply.started":"2021-06-01T16:21:40.172896Z","shell.execute_reply":"2021-06-01T16:21:40.180425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    import efficientnet_pytorch\nexcept ModuleNotFoundError:\n    !pip install -q \"../input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master\"","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:40.184230Z","iopub.execute_input":"2021-06-01T16:21:40.184497Z","iopub.status.idle":"2021-06-01T16:21:40.486252Z","shell.execute_reply.started":"2021-06-01T16:21:40.184472Z","shell.execute_reply":"2021-06-01T16:21:40.485469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport librosa as lb\nimport soundfile as sf\nimport pandas as pd\nimport cv2\nfrom pathlib import Path\nimport re\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\n\nimport torchvision\nfrom torchvision import models\n\nfrom tqdm.notebook import tqdm\n\nimport time\nfrom resnest.torch import resnest50\nfrom efficientnet_pytorch import EfficientNet","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","id":"kSCcqxf0c_O7","papermill":{"duration":4.153186,"end_time":"2021-02-16T15:59:57.894303","exception":false,"start_time":"2021-02-16T15:59:53.741117","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:40.489483Z","iopub.execute_input":"2021-06-01T16:21:40.489771Z","iopub.status.idle":"2021-06-01T16:21:41.332277Z","shell.execute_reply.started":"2021-06-01T16:21:40.489744Z","shell.execute_reply":"2021-06-01T16:21:41.331453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.046502,"end_time":"2021-02-16T15:59:59.284533","exception":false,"start_time":"2021-02-16T15:59:59.238031","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Configs","metadata":{"papermill":{"duration":0.046996,"end_time":"2021-02-16T15:59:59.377834","exception":false,"start_time":"2021-02-16T15:59:59.330838","status":"completed"},"tags":[]}},{"cell_type":"code","source":"NUM_CLASSES = 397\nSR = 32_000\nDURATION = 5\nTHRESH = 0.15\n\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"DEVICE:\", DEVICE)\n\nTEST_AUDIO_ROOT = Path(\"../input/birdclef-2021/test_soundscapes\")\nSAMPLE_SUB_PATH = \"../input/birdclef-2021/sample_submission.csv\"\nTARGET_PATH = None\n    \nif not len(list(TEST_AUDIO_ROOT.glob(\"*.ogg\"))):\n    TEST_AUDIO_ROOT = Path(\"../input/birdclef-2021/train_soundscapes\")\n    SAMPLE_SUB_PATH = None\n    # SAMPLE_SUB_PATH = \"../input/birdclef-2021/sample_submission.csv\"\n    TARGET_PATH = Path(\"../input/birdclef-2021/train_soundscape_labels.csv\")","metadata":{"id":"rJhYZVIDc_O9","papermill":{"duration":0.440614,"end_time":"2021-02-16T15:59:59.86408","exception":false,"start_time":"2021-02-16T15:59:59.423466","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:41.334563Z","iopub.execute_input":"2021-06-01T16:21:41.334863Z","iopub.status.idle":"2021-06-01T16:21:41.365794Z","shell.execute_reply.started":"2021-06-01T16:21:41.334836Z","shell.execute_reply":"2021-06-01T16:21:41.364739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data","metadata":{"papermill":{"duration":0.046026,"end_time":"2021-02-16T16:00:00.054107","exception":false,"start_time":"2021-02-16T16:00:00.008081","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class MelSpecComputer:\n    def __init__(self, sr, n_mels, fmin, fmax, **kwargs):\n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax\n        kwargs[\"n_fft\"] = kwargs.get(\"n_fft\", self.sr//10)\n        kwargs[\"hop_length\"] = kwargs.get(\"hop_length\", self.sr//(10*4))\n        self.kwargs = kwargs\n\n    def __call__(self, y):\n\n        melspec = lb.feature.melspectrogram(\n            y, sr=self.sr, n_mels=self.n_mels, fmin=self.fmin, fmax=self.fmax, **self.kwargs,\n        )\n\n        melspec = lb.power_to_db(melspec).astype(np.float32)\n        return melspec","metadata":{"id":"4fwNhdbJc_O-","papermill":{"duration":0.056975,"end_time":"2021-02-16T16:00:00.157168","exception":false,"start_time":"2021-02-16T16:00:00.100193","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:41.370301Z","iopub.execute_input":"2021-06-01T16:21:41.370891Z","iopub.status.idle":"2021-06-01T16:21:41.378013Z","shell.execute_reply.started":"2021-06-01T16:21:41.370851Z","shell.execute_reply":"2021-06-01T16:21:41.377350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def mono_to_color(X, eps=1e-6, mean=None, std=None):\n    mean = mean or X.mean()\n    std = std or X.std()\n    X = (X - mean) / (std + eps)\n    \n    _min, _max = X.min(), X.max()\n\n    if (_max - _min) > eps:\n        V = np.clip(X, _min, _max)\n        V = 255 * (V - _min) / (_max - _min)\n        V = V.astype(np.uint8)\n    else:\n        V = np.zeros_like(X, dtype=np.uint8)\n\n    return V\n\ndef crop_or_pad(y, length):\n    if len(y) < length:\n        y = np.concatenate([y, length - np.zeros(len(y))])\n    elif len(y) > length:\n        y = y[:length]\n    return y","metadata":{"id":"Nk0haSTIc_O_","papermill":{"duration":0.065406,"end_time":"2021-02-16T16:00:00.271104","exception":false,"start_time":"2021-02-16T16:00:00.205698","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:41.379992Z","iopub.execute_input":"2021-06-01T16:21:41.380335Z","iopub.status.idle":"2021-06-01T16:21:41.391214Z","shell.execute_reply.started":"2021-06-01T16:21:41.380300Z","shell.execute_reply":"2021-06-01T16:21:41.390487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class BirdCLEFDataset(Dataset):\n    def __init__(self, data, sr=SR, n_mels=128, fmin=0, fmax=None, duration=DURATION, step=None, res_type=\"kaiser_fast\", resample=True):\n        \n        self.data = data\n        \n        self.sr = sr\n        self.n_mels = n_mels\n        self.fmin = fmin\n        self.fmax = fmax or self.sr//2\n\n        self.duration = duration\n        self.audio_length = self.duration*self.sr\n        self.step = step or self.audio_length\n        \n        self.res_type = res_type\n        self.resample = resample\n\n        self.mel_spec_computer = MelSpecComputer(sr=self.sr, n_mels=self.n_mels, fmin=self.fmin,\n                                                 fmax=self.fmax)\n    def __len__(self):\n        return len(self.data)\n    \n    @staticmethod\n    def normalize(image):\n        image = image.astype(\"float32\", copy=False) / 255.0\n        image = np.stack([image, image, image])\n        return image\n    \n    def audio_to_image(self, audio):\n        melspec = self.mel_spec_computer(audio) \n        image = mono_to_color(melspec)\n        image = self.normalize(image)\n        return image\n\n    def read_file(self, filepath):\n        audio, orig_sr = sf.read(filepath, dtype=\"float32\")\n\n        if self.resample and orig_sr != self.sr:\n            audio = lb.resample(audio, orig_sr, self.sr, res_type=self.res_type)\n          \n        audios = []\n        for i in range(self.audio_length, len(audio) + self.step, self.step):\n            start = max(0, i - self.audio_length)\n            end = start + self.audio_length\n            audios.append(audio[start:end])\n            \n        if len(audios[-1]) < self.audio_length:\n            audios = audios[:-1]\n            \n        images = [self.audio_to_image(audio) for audio in audios]\n        images = np.stack(images)\n        \n        return images\n    \n        \n    def __getitem__(self, idx):\n        return self.read_file(self.data.loc[idx, \"filepath\"])","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:41.392829Z","iopub.execute_input":"2021-06-01T16:21:41.393185Z","iopub.status.idle":"2021-06-01T16:21:41.407615Z","shell.execute_reply.started":"2021-06-01T16:21:41.393149Z","shell.execute_reply":"2021-06-01T16:21:41.406813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.DataFrame(\n     [(path.stem, *path.stem.split(\"_\"), path) for path in Path(TEST_AUDIO_ROOT).glob(\"*.ogg\")],\n    columns = [\"filename\", \"id\", \"site\", \"date\", \"filepath\"]\n)\nprint(data.shape)\ndata.head()","metadata":{"id":"rVwlOrbxc_PD","outputId":"9b53ec99-634a-4b30-f9b5-75036184482b","papermill":{"duration":0.162256,"end_time":"2021-02-16T16:00:01.102152","exception":false,"start_time":"2021-02-16T16:00:00.939896","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:41.409131Z","iopub.execute_input":"2021-06-01T16:21:41.409516Z","iopub.status.idle":"2021-06-01T16:21:41.438091Z","shell.execute_reply.started":"2021-06-01T16:21:41.409476Z","shell.execute_reply":"2021-06-01T16:21:41.437224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"../input/birdclef-2021/train_metadata.csv\")\n\nLABEL_IDS = {label: label_id for label_id,label in enumerate(sorted(df_train[\"primary_label\"].unique()))}\nINV_LABEL_IDS = {val: key for key,val in LABEL_IDS.items()}","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:41.439717Z","iopub.execute_input":"2021-06-01T16:21:41.440065Z","iopub.status.idle":"2021-06-01T16:21:41.674651Z","shell.execute_reply.started":"2021-06-01T16:21:41.440029Z","shell.execute_reply":"2021-06-01T16:21:41.673676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference","metadata":{"id":"BNsivZZZc_PG","papermill":{"duration":0.048675,"end_time":"2021-02-16T16:00:08.424781","exception":false,"start_time":"2021-02-16T16:00:08.376106","status":"completed"},"tags":[]}},{"cell_type":"code","source":"test_data = BirdCLEFDataset(data=data)\nlen(test_data), test_data[0].shape","metadata":{"id":"AzlOErOmc_PH","papermill":{"duration":0.058312,"end_time":"2021-02-16T16:00:08.531199","exception":false,"start_time":"2021-02-16T16:00:08.472887","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:41.676021Z","iopub.execute_input":"2021-06-01T16:21:41.676376Z","iopub.status.idle":"2021-06-01T16:21:44.712192Z","shell.execute_reply.started":"2021-06-01T16:21:41.676336Z","shell.execute_reply":"2021-06-01T16:21:44.711324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys \nsys.path.append('../input/timm-pytorch-image-models/pytorch-image-models-master') \nimport timm \nimport torch\nimport torch.nn as nn\n\nclass densenet(nn.Module):\n    def __init__(self, n_class=NUM_CLASSES, model_name='densenet121', pretrained=False):\n        super().__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained,num_classes=0)\n        self.dropout = torch.nn.Dropout(p=0.2)\n        self.classifier = nn.Linear(1024, n_class)\n\n    def forward(self, x):\n        x = self.model(x)\n        x = self.dropout(x)\n        x = self.classifier(x)\n        \n        return x\n\nclass nfnet(nn.Module):\n    def __init__(self, n_class=NUM_CLASSES, model_name='eca_nfnet_l0', pretrained=False):\n        super().__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained,num_classes=0)\n        self.dropout = torch.nn.Dropout(p=0.4)\n        self.classifier = nn.Linear(2304, n_class)\n\n    def forward(self, x):\n        x = self.model(x)\n        x = self.dropout(x)\n        x = self.classifier(x)\n        \n        return x","metadata":{"papermill":{"duration":0.048931,"end_time":"2021-02-16T16:00:14.351476","exception":false,"start_time":"2021-02-16T16:00:14.302545","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:44.713595Z","iopub.execute_input":"2021-06-01T16:21:44.714108Z","iopub.status.idle":"2021-06-01T16:21:45.333015Z","shell.execute_reply.started":"2021-06-01T16:21:44.714060Z","shell.execute_reply":"2021-06-01T16:21:45.332149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_resnest(checkpoint_path, num_classes=NUM_CLASSES):\n    net = resnest50(pretrained=False)\n    net.fc = nn.Linear(net.fc.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ndef load_nfnet(checkpoint_path, num_classes=NUM_CLASSES):\n    net = nfnet(pretrained=False)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n#     for key in list(d.keys()):\n#         d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ndef load_densenet(checkpoint_path, num_classes=NUM_CLASSES):\n#     net = densenet(pretrained=False)\n    net = models.densenet121(pretrained=False)\n    net.classifier = nn.Linear(net.classifier.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ndef load_resnet(checkpoint_path, num_classes=NUM_CLASSES):\n    net = models.resnet50(pretrained=False)\n    net.fc = nn.Linear(net.fc.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ndef load_resnest50d(checkpoint_path, num_classes=NUM_CLASSES):\n    net = timm.create_model('resnest50d',pretrained=False)\n    net.fc = nn.Linear(net.fc.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net\n\ndef load_efficient_net(checkpoint_path, num_classes=NUM_CLASSES):\n    net = EfficientNet.from_name('efficientnet-b4')\n    net._fc = nn.Linear(net._fc.in_features, num_classes)\n    dummy_device = torch.device(\"cpu\")\n    d = torch.load(checkpoint_path, map_location=dummy_device)\n    for key in list(d.keys()):\n        d[key.replace(\"model.\", \"\")] = d.pop(key)\n    net.load_state_dict(d)\n    net = net.to(DEVICE)\n    net = net.eval()\n    return net","metadata":{"papermill":{"duration":0.05945,"end_time":"2021-02-16T16:00:14.565804","exception":false,"start_time":"2021-02-16T16:00:14.506354","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:45.334509Z","iopub.execute_input":"2021-06-01T16:21:45.334861Z","iopub.status.idle":"2021-06-01T16:21:45.353750Z","shell.execute_reply.started":"2021-06-01T16:21:45.334822Z","shell.execute_reply":"2021-06-01T16:21:45.352271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncheckpoint_paths = [\n    Path(\"../input/kkiller-birdclef-models-public/birdclef_resnest50_fold0_epoch_10_f1_val_06471_20210417161101.pth\"),\n]\n\ncheckpoint_paths_efficient = [\n    Path(\"../input/birdclef-focal-loss/birdclef_efficientnet-b4_fold0_epoch_19_f1_val_07435_20210601040429.pth\"),\n]\n\ncheckpoint_paths_resnet = [\n    Path(\"../input/birdclef-resnet50-bce-adam/birdclef_resnet50_fold0_epoch_11_f1_val_07096_20210529175212.pth\"),\n]\n\ncheckpoint_paths_dense = [\n    Path(\"../input/birdclef-resnet50-bce-adam/birdclef_densenet121_fold0_epoch_11_f1_val_07409_20210601153956.pth\"),\n]\n\nnets = [\n    load_resnest(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths\n]\n\nnets_efficient = [\n    load_efficient_net(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths_efficient\n]\n\nnets_resnet = [\n    load_resnet(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths_resnet\n]\n\nnets_dense = [\n    load_densenet(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths_dense\n]\n\n\n# nets = [\n#         load_net(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths\n# ]","metadata":{"id":"ayVLRTzLc_PI","papermill":{"duration":14.506299,"end_time":"2021-02-16T16:00:30.268614","exception":false,"start_time":"2021-02-16T16:00:15.762315","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:45.355331Z","iopub.execute_input":"2021-06-01T16:21:45.355718Z","iopub.status.idle":"2021-06-01T16:21:49.256677Z","shell.execute_reply.started":"2021-06-01T16:21:45.355678Z","shell.execute_reply":"2021-06-01T16:21:49.255843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.051509,"end_time":"2021-02-16T16:00:30.373444","exception":false,"start_time":"2021-02-16T16:00:30.321935","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@torch.no_grad()\ndef get_thresh_preds(out, m, thresh=None):\n    #thresh = thresh or THRESH\n    if m == 1: # resnest\n        thresh = 0.1\n    elif m == 2: # efficient net\n        thresh = 0.25\n    elif m == 3: # resnet\n        thresh = 0.6\n    elif m == 4: # densenet\n        thresh = 0.75\n    elif m == 0:\n        thresh = thresh\n    o = (-out).argsort(1)\n    npreds = (out > thresh).sum(1)\n    preds = []\n    for oo, npred in zip(o, npreds):\n        preds.append(oo[:npred].cpu().numpy().tolist())\n    return preds","metadata":{"papermill":{"duration":0.059925,"end_time":"2021-02-16T16:00:30.912547","exception":false,"start_time":"2021-02-16T16:00:30.852622","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:49.257970Z","iopub.execute_input":"2021-06-01T16:21:49.258303Z","iopub.status.idle":"2021-06-01T16:21:49.266085Z","shell.execute_reply.started":"2021-06-01T16:21:49.258268Z","shell.execute_reply":"2021-06-01T16:21:49.263502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_bird_names(preds):\n    bird_names = []\n    for pred in preds:\n        if not pred:\n            bird_names.append(\"nocall\")\n        else:\n            bird_names.append(\" \".join([INV_LABEL_IDS[bird_id] for bird_id in pred]))\n    return bird_names","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:49.268272Z","iopub.execute_input":"2021-06-01T16:21:49.268645Z","iopub.status.idle":"2021-06-01T16:21:49.278875Z","shell.execute_reply.started":"2021-06-01T16:21:49.268597Z","shell.execute_reply":"2021-06-01T16:21:49.277865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict(nets, test_data, m, names=True):\n    preds = []\n    with torch.no_grad():\n        for idx in  tqdm(list(range(len(test_data)))):\n            xb = torch.from_numpy(test_data[idx]).to(DEVICE)\n            pred = 0.\n            for net in nets:\n                o = net(xb)\n                o = torch.sigmoid(o)\n\n                pred += o\n\n            pred /= len(nets)\n            \n            if names:\n                pred = get_bird_names(get_thresh_preds(pred, m))\n\n            preds.append(pred)\n    return preds","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:21:49.280194Z","iopub.execute_input":"2021-06-01T16:21:49.280820Z","iopub.status.idle":"2021-06-01T16:21:49.288615Z","shell.execute_reply.started":"2021-06-01T16:21:49.280783Z","shell.execute_reply":"2021-06-01T16:21:49.287996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas = predict(nets, test_data, 1, names=False)","metadata":{"papermill":{"duration":7466.932385,"end_time":"2021-02-16T18:04:58.116349","exception":false,"start_time":"2021-02-16T16:00:31.183964","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-06-01T16:21:49.290006Z","iopub.execute_input":"2021-06-01T16:21:49.290507Z","iopub.status.idle":"2021-06-01T16:22:47.330678Z","shell.execute_reply.started":"2021-06-01T16:21:49.290470Z","shell.execute_reply":"2021-06-01T16:22:47.329738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas_efficient = predict(nets_efficient, test_data, 2, names=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:22:47.333699Z","iopub.execute_input":"2021-06-01T16:22:47.336763Z","iopub.status.idle":"2021-06-01T16:23:45.299234Z","shell.execute_reply.started":"2021-06-01T16:22:47.336714Z","shell.execute_reply":"2021-06-01T16:23:45.298248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas_resnet = predict(nets_resnet, test_data, 3, names=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:23:45.300786Z","iopub.execute_input":"2021-06-01T16:23:45.301337Z","iopub.status.idle":"2021-06-01T16:24:42.251163Z","shell.execute_reply.started":"2021-06-01T16:23:45.301296Z","shell.execute_reply":"2021-06-01T16:24:42.250174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas_dense = predict(nets_dense, test_data, 4, names=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:24:42.252710Z","iopub.execute_input":"2021-06-01T16:24:42.253339Z","iopub.status.idle":"2021-06-01T16:25:39.691178Z","shell.execute_reply.started":"2021-06-01T16:24:42.253300Z","shell.execute_reply":"2021-06-01T16:25:39.690247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_probas_avg =[(pred_probas[i]*7 + pred_probas_efficient[i]*1 + pred_probas_resnet[i]*1 + pred_probas_dense[i]*1)/10 for i in range(0,len(pred_probas))]","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.694237Z","iopub.execute_input":"2021-06-01T16:25:39.697390Z","iopub.status.idle":"2021-06-01T16:25:39.707294Z","shell.execute_reply.started":"2021-06-01T16:25:39.697344Z","shell.execute_reply":"2021-06-01T16:25:39.706417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# preds = [get_bird_names(get_thresh_preds(pred, thresh=0.1)) for pred in pred_probas]\n# preds_efficient = [get_bird_names(get_thresh_preds(pred, thresh=0.25)) for pred in pred_probas_efficient]\n# preds_resnet = [get_bird_names(get_thresh_preds(pred, thresh=0.6)) for pred in pred_probas_resnet]\npreds_avg = [get_bird_names(get_thresh_preds(pred, 0, thresh=0.15)) for pred in pred_probas_avg]\n# preds[:2]","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.711842Z","iopub.execute_input":"2021-06-01T16:25:39.714320Z","iopub.status.idle":"2021-06-01T16:25:39.833070Z","shell.execute_reply.started":"2021-06-01T16:25:39.714277Z","shell.execute_reply":"2021-06-01T16:25:39.832407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preds_as_df(data, preds):\n    sub = {\n        \"row_id\": [],\n        \"birds\": [],\n    }\n    \n    for row, pred in zip(data.itertuples(False), preds):\n        row_id = [f\"{row.id}_{row.site}_{5*i}\" for i in range(1, len(pred)+1)]\n        sub[\"birds\"] += pred\n        sub[\"row_id\"] += row_id\n        \n    sub = pd.DataFrame(sub)\n    \n    if SAMPLE_SUB_PATH:\n        sample_sub = pd.read_csv(SAMPLE_SUB_PATH, usecols=[\"row_id\"])\n        sub = sample_sub.merge(sub, on=\"row_id\", how=\"left\")\n        sub[\"birds\"] = sub[\"birds\"].fillna(\"nocall\")\n    return sub","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.834183Z","iopub.execute_input":"2021-06-01T16:25:39.834485Z","iopub.status.idle":"2021-06-01T16:25:39.841442Z","shell.execute_reply.started":"2021-06-01T16:25:39.834455Z","shell.execute_reply":"2021-06-01T16:25:39.840552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = preds_as_df(data, preds_avg)\nprint(sub.shape)\nsub","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.842864Z","iopub.execute_input":"2021-06-01T16:25:39.843427Z","iopub.status.idle":"2021-06-01T16:25:39.861773Z","shell.execute_reply.started":"2021-06-01T16:25:39.843389Z","shell.execute_reply":"2021-06-01T16:25:39.860806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.862952Z","iopub.execute_input":"2021-06-01T16:25:39.863454Z","iopub.status.idle":"2021-06-01T16:25:39.984575Z","shell.execute_reply.started":"2021-06-01T16:25:39.863417Z","shell.execute_reply":"2021-06-01T16:25:39.983846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Small validation","metadata":{}},{"cell_type":"code","source":"def get_metrics(s_true, s_pred):\n    s_true = set(s_true.split())\n    s_pred = set(s_pred.split())\n    n, n_true, n_pred = len(s_true.intersection(s_pred)), len(s_true), len(s_pred)\n    \n    prec = n/n_pred\n    rec = n/n_true\n    f1 = 2*prec*rec/(prec + rec) if prec + rec else 0\n    \n    return {\"f1\": f1, \"prec\": prec, \"rec\": rec, \"n_true\": n_true, \"n_pred\": n_pred, \"n\": n}","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.985841Z","iopub.execute_input":"2021-06-01T16:25:39.986270Z","iopub.status.idle":"2021-06-01T16:25:39.994163Z","shell.execute_reply.started":"2021-06-01T16:25:39.986233Z","shell.execute_reply":"2021-06-01T16:25:39.993422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# THRESH CV\n\n# for i in range(20):\n#     THRESH = i*0.05\n#     print(\"preds_dense THRESH:\", THRESH)\n#     preds_dense = [get_bird_names(get_thresh_preds(pred, 0, thresh=THRESH)) for pred in pred_probas_dense]\n#     sub = preds_as_df(data, preds_dense)\n#     print(sub.shape)\n#     sub.to_csv(\"submission.csv\", index=False)\n    \n#     if TARGET_PATH:\n#         sub_target = pd.read_csv(TARGET_PATH)\n#         sub_target = sub_target.merge(sub, how=\"left\", on=\"row_id\")\n    \n#         print(sub_target[\"birds_x\"].notnull().sum(), sub_target[\"birds_x\"].notnull().sum())\n#         assert sub_target[\"birds_x\"].notnull().all()\n#         assert sub_target[\"birds_y\"].notnull().all()\n    \n#         df_metrics = pd.DataFrame([get_metrics(s_true, s_pred) for s_true, s_pred in zip(sub_target.birds_x, sub_target.birds_y)])\n    \n#         print(df_metrics.mean())\n#         print()","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:39.995341Z","iopub.execute_input":"2021-06-01T16:25:39.995821Z","iopub.status.idle":"2021-06-01T16:25:40.002716Z","shell.execute_reply.started":"2021-06-01T16:25:39.995791Z","shell.execute_reply":"2021-06-01T16:25:40.002076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for i in range(20):\n#     THRESH = i*0.05\n#     print(\"preds_avg THRESH:\", THRESH)\n#     preds_avg = [get_bird_names(get_thresh_preds(pred, 0, thresh=THRESH)) for pred in pred_probas_avg]\n#     sub = preds_as_df(data, preds_avg)\n#     print(sub.shape)\n#     sub.to_csv(\"submission.csv\", index=False)\n    \n#     if TARGET_PATH:\n#         sub_target = pd.read_csv(TARGET_PATH)\n#         sub_target = sub_target.merge(sub, how=\"left\", on=\"row_id\")\n    \n#         print(sub_target[\"birds_x\"].notnull().sum(), sub_target[\"birds_x\"].notnull().sum())\n#         assert sub_target[\"birds_x\"].notnull().all()\n#         assert sub_target[\"birds_y\"].notnull().all()\n    \n#         df_metrics = pd.DataFrame([get_metrics(s_true, s_pred) for s_true, s_pred in zip(sub_target.birds_x, sub_target.birds_y)])\n    \n#         print(df_metrics.mean())\n#         print()","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:40.004116Z","iopub.execute_input":"2021-06-01T16:25:40.004592Z","iopub.status.idle":"2021-06-01T16:25:40.015484Z","shell.execute_reply.started":"2021-06-01T16:25:40.004555Z","shell.execute_reply":"2021-06-01T16:25:40.014565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if TARGET_PATH:\n    sub_target = pd.read_csv(TARGET_PATH)\n    sub_target = sub_target.merge(sub, how=\"left\", on=\"row_id\")\n    \n    print(sub_target[\"birds_x\"].notnull().sum(), sub_target[\"birds_x\"].notnull().sum())\n    assert sub_target[\"birds_x\"].notnull().all()\n    assert sub_target[\"birds_y\"].notnull().all()\n    \n    df_metrics = pd.DataFrame([get_metrics(s_true, s_pred) for s_true, s_pred in zip(sub_target.birds_x, sub_target.birds_y)])\n    \n    print(df_metrics.mean())","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:40.016827Z","iopub.execute_input":"2021-06-01T16:25:40.017233Z","iopub.status.idle":"2021-06-01T16:25:40.054748Z","shell.execute_reply.started":"2021-06-01T16:25:40.017197Z","shell.execute_reply":"2021-06-01T16:25:40.054029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_target[sub_target.birds_y != \"nocall\"]","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:40.057433Z","iopub.execute_input":"2021-06-01T16:25:40.057675Z","iopub.status.idle":"2021-06-01T16:25:40.076654Z","shell.execute_reply.started":"2021-06-01T16:25:40.057651Z","shell.execute_reply":"2021-06-01T16:25:40.075795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_target[sub_target.birds_x != \"nocall\"]","metadata":{"execution":{"iopub.status.busy":"2021-06-01T16:25:40.079825Z","iopub.execute_input":"2021-06-01T16:25:40.080061Z","iopub.status.idle":"2021-06-01T16:25:40.097857Z","shell.execute_reply.started":"2021-06-01T16:25:40.080037Z","shell.execute_reply":"2021-06-01T16:25:40.097133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}