{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":25954,"databundleVersionId":2091745,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":13752467,"sourceType":"datasetVersion","datasetId":8750870},{"sourceId":13757085,"sourceType":"datasetVersion","datasetId":8751379},{"sourceId":13764846,"sourceType":"datasetVersion","datasetId":8759945}],"dockerImageVersionId":31192,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport librosa as lb\nimport librosa.display as lbd\nimport soundfile as sf\nfrom  soundfile import SoundFile\nimport pandas as pd\nfrom  IPython.display import Audio\nfrom pathlib import Path\n\nimport torch\nfrom torch import nn, optim\nfrom  torch.utils.data import Dataset, DataLoader\nimport torchvision.models as models\n\nfrom matplotlib import pyplot as plt\n\nimport os, random, gc\nimport re, time, json\nfrom  ast import literal_eval\n\nfrom IPython.display import Audio\nfrom sklearn.metrics import label_ranking_average_precision_score\n\nfrom tqdm.notebook import tqdm\nimport joblib","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:14.897974Z","iopub.execute_input":"2025-11-16T10:56:14.898187Z","iopub.status.idle":"2025-11-16T10:56:24.676473Z","shell.execute_reply.started":"2025-11-16T10:56:14.898170Z","shell.execute_reply":"2025-11-16T10:56:24.675925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NUM_CLASSES = 397\nSR = 32000\nDURATION = 5\nTHRESH = 0.25\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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:24.677746Z","iopub.execute_input":"2025-11-16T10:56:24.678199Z","iopub.status.idle":"2025-11-16T10:56:24.778641Z","shell.execute_reply.started":"2025-11-16T10:56:24.678180Z","shell.execute_reply":"2025-11-16T10:56:24.777873Z"}},"outputs":[],"execution_count":null},{"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=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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:54.659556Z","iopub.execute_input":"2025-11-16T10:56:54.660155Z","iopub.status.idle":"2025-11-16T10:56:54.665258Z","shell.execute_reply.started":"2025-11-16T10:56:54.660108Z","shell.execute_reply":"2025-11-16T10:56:54.664540Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:24.791852Z","iopub.execute_input":"2025-11-16T10:56:24.792068Z","iopub.status.idle":"2025-11-16T10:56:24.802808Z","shell.execute_reply.started":"2025-11-16T10:56:24.792052Z","shell.execute_reply":"2025-11-16T10:56:24.802107Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:24.803693Z","iopub.execute_input":"2025-11-16T10:56:24.804424Z","iopub.status.idle":"2025-11-16T10:56:24.818048Z","shell.execute_reply.started":"2025-11-16T10:56:24.804393Z","shell.execute_reply":"2025-11-16T10:56:24.817273Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:24.818706Z","iopub.execute_input":"2025-11-16T10:56:24.818963Z","iopub.status.idle":"2025-11-16T10:56:24.857546Z","shell.execute_reply.started":"2025-11-16T10:56:24.818942Z","shell.execute_reply":"2025-11-16T10:56:24.857020Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:24.859435Z","iopub.execute_input":"2025-11-16T10:56:24.859621Z","iopub.status.idle":"2025-11-16T10:56:25.294581Z","shell.execute_reply.started":"2025-11-16T10:56:24.859606Z","shell.execute_reply":"2025-11-16T10:56:25.294033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data = BirdCLEFDataset(data=data)\nlen(test_data), test_data[0].shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:56:58.459683Z","iopub.execute_input":"2025-11-16T10:56:58.460485Z","iopub.status.idle":"2025-11-16T10:57:00.641425Z","shell.execute_reply.started":"2025-11-16T10:56:58.460460Z","shell.execute_reply":"2025-11-16T10:57:00.640661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_net(checkpoint_path, num_classes=NUM_CLASSES):\n    net = models.resnet50(weights=None)\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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:10.471346Z","iopub.execute_input":"2025-11-16T10:57:10.471628Z","iopub.status.idle":"2025-11-16T10:57:10.476792Z","shell.execute_reply.started":"2025-11-16T10:57:10.471607Z","shell.execute_reply":"2025-11-16T10:57:10.476011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"checkpoint_paths = [\n    Path('/kaggle/input/birdclef-2021-resnet50-10-epochs/resnet_sr32000_d7_v1_v1/birdclef_resnet_fold0_epoch_08_f1_val_07225_20251117110144.pth'),\n]\n\n\nnets = [\n        load_net(checkpoint_path.as_posix()) for checkpoint_path in checkpoint_paths\n]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:10.478090Z","iopub.execute_input":"2025-11-16T10:57:10.478692Z","iopub.status.idle":"2025-11-16T10:57:11.273022Z","shell.execute_reply.started":"2025-11-16T10:57:10.478665Z","shell.execute_reply":"2025-11-16T10:57:11.272406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"@torch.no_grad()\ndef get_thresh_preds(out, thresh=None):\n    thresh = thresh or 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:11.273756Z","iopub.execute_input":"2025-11-16T10:57:11.274010Z","iopub.status.idle":"2025-11-16T10:57:11.278839Z","shell.execute_reply.started":"2025-11-16T10:57:11.273988Z","shell.execute_reply":"2025-11-16T10:57:11.278110Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:11.280294Z","iopub.execute_input":"2025-11-16T10:57:11.280532Z","iopub.status.idle":"2025-11-16T10:57:11.293312Z","shell.execute_reply.started":"2025-11-16T10:57:11.280508Z","shell.execute_reply":"2025-11-16T10:57:11.292681Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict(nets, test_data, 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))\n\n            preds.append(pred)\n    return preds","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:11.294086Z","iopub.execute_input":"2025-11-16T10:57:11.294856Z","iopub.status.idle":"2025-11-16T10:57:11.304486Z","shell.execute_reply.started":"2025-11-16T10:57:11.294832Z","shell.execute_reply":"2025-11-16T10:57:11.303828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_probas = predict(nets, test_data, names=False)\nprint(len(pred_probas))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:11.305170Z","iopub.execute_input":"2025-11-16T10:57:11.305378Z","iopub.status.idle":"2025-11-16T10:57:55.425553Z","shell.execute_reply.started":"2025-11-16T10:57:11.305360Z","shell.execute_reply":"2025-11-16T10:57:55.424631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds = [get_bird_names(get_thresh_preds(pred, thresh=THRESH)) for pred in pred_probas]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:55.426511Z","iopub.execute_input":"2025-11-16T10:57:55.426796Z","iopub.status.idle":"2025-11-16T10:57:55.700474Z","shell.execute_reply.started":"2025-11-16T10:57:55.426767Z","shell.execute_reply":"2025-11-16T10:57:55.699927Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:55.701184Z","iopub.execute_input":"2025-11-16T10:57:55.701381Z","iopub.status.idle":"2025-11-16T10:57:55.706682Z","shell.execute_reply.started":"2025-11-16T10:57:55.701365Z","shell.execute_reply":"2025-11-16T10:57:55.705983Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub = preds_as_df(data, preds)\nprint(sub.shape)\nsub","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:55.708452Z","iopub.execute_input":"2025-11-16T10:57:55.709089Z","iopub.status.idle":"2025-11-16T10:57:55.730578Z","shell.execute_reply.started":"2025-11-16T10:57:55.709062Z","shell.execute_reply":"2025-11-16T10:57:55.730013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-16T10:57:55.731246Z","iopub.execute_input":"2025-11-16T10:57:55.731425Z","iopub.status.idle":"2025-11-16T10:57:55.742353Z","shell.execute_reply.started":"2025-11-16T10:57:55.731411Z","shell.execute_reply":"2025-11-16T10:57:55.741674Z"}},"outputs":[],"execution_count":null}]}