{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":91844,"databundleVersionId":11361821,"sourceType":"competition"},{"sourceId":11828260,"sourceType":"datasetVersion","datasetId":7430593}],"dockerImageVersionId":30918,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false},"papermill":{"default_parameters":{},"duration":27.447062,"end_time":"2025-03-12T14:13:11.647927","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2025-03-12T14:12:44.200865","version":"2.6.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Post-Processing with Power Adjustment for Low-Ranked Classes\nThis notebook demonstrates a simple post-processing method applied during inference. \nWhile this improves the LB score, please note that it may be overfitting to the leaderboard.","metadata":{}},{"cell_type":"markdown","source":"# Post-Processing Function","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom typing import Union\n\ndef apply_power_to_low_ranked_cols(\n    p: np.ndarray,\n    top_k: int = 30,\n    exponent: Union[int, float] = 2,\n    inplace: bool = True\n) -> np.ndarray:\n    \"\"\"\n    Rank columns by their column‑wise maximum and raise every column whose\n    rank falls below `top_k` to a given power.\n\n    Parameters\n    ----------\n    p : np.ndarray\n        A 2‑D array of shape **(n_chunks, n_classes)**.\n\n        - **n_chunks** is the number of fixed‑length time chunks obtained\n          after slicing the input audio (or other sequential data).  \n          *Example:* In the BirdCLEF `test_soundscapes` set, each file is\n          60 s long. If you extract non‑overlapping 5 s windows,  \n          `n_chunks = 60 s / 5 s = 12`.\n        - **n_classes** is the number of classes being predicted.\n        - Each element `p[i, j]` is the score or probability of class *j*\n          in chunk *i*.\n\n    top_k : int, default=30\n        The highest‑ranked columns (by their maximum value) that remain\n        unchanged.\n\n    exponent : int or float, default=2\n        The power applied to the selected low‑ranked columns  \n        (e.g. `2` squares, `0.5` takes the square root, `3` cubes).\n\n    inplace : bool, default=True\n        If `True`, modify `p` in place.  \n        If `False`, operate on a copy and leave the original array intact.\n\n    Returns\n    -------\n    np.ndarray\n        The transformed array. It is the same object as `p` when\n        `inplace=True`; otherwise, it is a new array.\n\n    \"\"\"\n    if not inplace:\n        p = p.copy()\n\n    # Identify columns whose max value ranks below `top_k`\n    tail_cols = np.argsort(-p.max(axis=0))[top_k:]\n\n    # Apply the power transformation to those columns\n    p[:, tail_cols] = p[:, tail_cols] ** exponent\n    return p","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.080614Z","iopub.execute_input":"2025-05-15T20:42:18.081068Z","iopub.status.idle":"2025-05-15T20:42:18.088986Z","shell.execute_reply.started":"2025-05-15T20:42:18.081034Z","shell.execute_reply":"2025-05-15T20:42:18.087574Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Import","metadata":{}},{"cell_type":"code","source":"import os\nimport gc\nimport time\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport timm\nimport torch.nn.functional as F\nimport torchaudio\nimport torchaudio.transforms as AT\nfrom contextlib import contextmanager\nimport concurrent.futures","metadata":{"papermill":{"duration":12.984639,"end_time":"2025-03-12T14:13:00.145177","exception":false,"start_time":"2025-03-12T14:12:47.160538","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.090582Z","iopub.execute_input":"2025-05-15T20:42:18.090941Z","iopub.status.idle":"2025-05-15T20:42:18.123248Z","shell.execute_reply.started":"2025-05-15T20:42:18.090913Z","shell.execute_reply":"2025-05-15T20:42:18.122056Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Load data","metadata":{}},{"cell_type":"code","source":"test_audio_dir = '../input/birdclef-2025/test_soundscapes/'\nfile_list = [f for f in sorted(os.listdir(test_audio_dir))]\nfile_list = [file.split('.')[0] for file in file_list if file.endswith('.ogg')]\n\ndebug = False\nif len(file_list) == 0:\n    debug = True\n    debug_st_num = 5\n    debug_num = 8\n    test_audio_dir = '../input/birdclef-2025/train_soundscapes/'\n    file_list = [f for f in sorted(os.listdir(test_audio_dir))]\n    file_list = [file.split('.')[0] for file in file_list if file.endswith('.ogg')]\n    file_list = file_list[debug_st_num:debug_st_num+debug_num]\n\nprint('Debug mode:', debug)\nprint('Number of test soundscapes:', len(file_list))","metadata":{"papermill":{"duration":0.105385,"end_time":"2025-03-12T14:13:00.253425","exception":false,"start_time":"2025-03-12T14:13:00.14804","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.125654Z","iopub.execute_input":"2025-05-15T20:42:18.125982Z","iopub.status.idle":"2025-05-15T20:42:18.223625Z","shell.execute_reply.started":"2025-05-15T20:42:18.125953Z","shell.execute_reply":"2025-05-15T20:42:18.221952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"wav_sec = 5\nsample_rate = 32000\nmin_segment = sample_rate*wav_sec\n\nclass_labels = sorted(os.listdir('../input/birdclef-2025/train_audio/'))\n\nn_fft=1024\nwin_length=1024\nhop_length=512\nf_min=50\nf_max=16000\nn_mels=128\n\nmel_spectrogram = AT.MelSpectrogram(\n    sample_rate=sample_rate,\n    n_fft=n_fft,\n    win_length=win_length,\n    hop_length=hop_length,\n    center=True,\n    f_min=f_min,\n    f_max=f_max,\n    pad_mode=\"reflect\",\n    power=2.0,\n    norm='slaney',\n    n_mels=n_mels,\n    mel_scale=\"htk\",\n    # normalized=True\n)\n\ndef normalize_std(spec, eps=1e-6):\n    mean = torch.mean(spec)\n    std = torch.std(spec)\n    return torch.where(std == 0, spec-mean, (spec - mean) / (std+eps))\n\ndef audio_to_mel(filepath=None):\n    waveform, sample_rate = torchaudio.load(filepath,backend=\"soundfile\")\n    len_wav = waveform.shape[1]\n    waveform = waveform[0,:].reshape(1, len_wav) # stereo->mono mono->mono\n    PREDS = []\n    for i in range(12):\n        waveform2 = waveform[:,i*sample_rate*5:i*sample_rate*5+sample_rate*5]\n        melspec = mel_spectrogram(waveform2)\n        melspec = torch.log(melspec+1e-6)\n        melspec = normalize_std(melspec)\n        melspec = torch.unsqueeze(melspec, dim=0)\n        \n        PREDS.append(melspec)\n    return torch.vstack(PREDS)","metadata":{"papermill":{"duration":0.144235,"end_time":"2025-03-12T14:13:00.400505","exception":false,"start_time":"2025-03-12T14:13:00.25627","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.225943Z","iopub.execute_input":"2025-05-15T20:42:18.226297Z","iopub.status.idle":"2025-05-15T20:42:18.238776Z","shell.execute_reply.started":"2025-05-15T20:42:18.226269Z","shell.execute_reply":"2025-05-15T20:42:18.237396Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"def init_layer(layer):\n    nn.init.xavier_uniform_(layer.weight)\n    if hasattr(layer, \"bias\"):\n        if layer.bias is not None:\n            layer.bias.data.fill_(0.)\n\n\ndef init_bn(bn):\n    bn.bias.data.fill_(0.)\n    bn.weight.data.fill_(1.0)\n\n\ndef init_weights(model):\n    classname = model.__class__.__name__\n    if classname.find(\"Conv2d\") != -1:\n        nn.init.xavier_uniform_(model.weight, gain=np.sqrt(2))\n        model.bias.data.fill_(0)\n    elif classname.find(\"BatchNorm\") != -1:\n        model.weight.data.normal_(1.0, 0.02)\n        model.bias.data.fill_(0)\n    elif classname.find(\"GRU\") != -1:\n        for weight in model.parameters():\n            if len(weight.size()) > 1:\n                nn.init.orghogonal_(weight.data)\n    elif classname.find(\"Linear\") != -1:\n        model.weight.data.normal_(0, 0.01)\n        model.bias.data.zero_()\n\n\ndef interpolate(x, ratio):\n    (batch_size, time_steps, classes_num) = x.shape\n    upsampled = x[:, :, None, :].repeat(1, 1, ratio, 1)\n    upsampled = upsampled.reshape(batch_size, time_steps * ratio, classes_num)\n    return upsampled\n\n\ndef pad_framewise_output(framewise_output, frames_num):\n    output = F.interpolate(\n        framewise_output.unsqueeze(1),\n        size=(frames_num, framewise_output.size(2)),\n        align_corners=True,\n        mode=\"bilinear\").squeeze(1)\n\n    return output\n\n\nclass AttBlockV2(nn.Module):\n    def __init__(self,\n                 in_features: int,\n                 out_features: int,\n                 activation=\"linear\"):\n        super().__init__()\n\n        self.activation = activation\n        self.att = nn.Conv1d(\n            in_channels=in_features,\n            out_channels=out_features,\n            kernel_size=1,\n            stride=1,\n            padding=0,\n            bias=True)\n        self.cla = nn.Conv1d(\n            in_channels=in_features,\n            out_channels=out_features,\n            kernel_size=1,\n            stride=1,\n            padding=0,\n            bias=True)\n\n        self.init_weights()\n\n    def init_weights(self):\n        init_layer(self.att)\n        init_layer(self.cla)\n\n    def forward(self, x):\n        norm_att = torch.softmax(torch.tanh(self.att(x)), dim=-1)\n        cla = self.nonlinear_transform(self.cla(x))\n        x = torch.sum(norm_att * cla, dim=2)\n        return x, norm_att, cla\n\n    def nonlinear_transform(self, x):\n        if self.activation == 'linear':\n            return x\n        elif self.activation == 'sigmoid':\n            return torch.sigmoid(x)\n\n\nclass TimmSED(nn.Module):\n    def __init__(self, base_model_name: str, pretrained=False, num_classes=24, in_channels=1, n_mels=24):\n        super().__init__()\n\n        self.bn0 = nn.BatchNorm2d(n_mels)\n\n        base_model = timm.create_model(\n            base_model_name, pretrained=pretrained, in_chans=in_channels)\n        layers = list(base_model.children())[:-2]\n        self.encoder = nn.Sequential(*layers)\n\n        in_features = base_model.num_features\n\n        self.fc1 = nn.Linear(in_features, in_features, bias=True)\n        self.att_block2 = AttBlockV2(\n            in_features, num_classes, activation=\"sigmoid\")\n\n        self.init_weight()\n\n    def init_weight(self):\n        init_bn(self.bn0)\n        init_layer(self.fc1)\n        \n\n    def forward(self, input_data):\n        x = input_data.transpose(2,3)\n        x = torch.cat((x,x,x),1)\n\n        x = x.transpose(2, 3)\n\n        x = self.encoder(x)\n        \n        x = torch.mean(x, dim=2)\n\n        x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)\n        x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)\n        x = x1 + x2\n\n        x = x.transpose(1, 2)\n        x = F.relu_(self.fc1(x))\n        x = x.transpose(1, 2)\n\n        (clipwise_output, norm_att, segmentwise_output) = self.att_block2(x)\n        logit = torch.sum(norm_att * self.att_block2.cla(x), dim=2)\n\n        output_dict = {\n            'logit': logit,\n        }\n\n        return output_dict","metadata":{"papermill":{"duration":2.175154,"end_time":"2025-03-12T14:13:02.578522","exception":false,"start_time":"2025-03-12T14:13:00.403368","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.284107Z","iopub.execute_input":"2025-05-15T20:42:18.284506Z","iopub.status.idle":"2025-05-15T20:42:18.308886Z","shell.execute_reply.started":"2025-05-15T20:42:18.284449Z","shell.execute_reply":"2025-05-15T20:42:18.306863Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model_name='eca_nfnet_l0'\npretrained=False\nin_channels=3\n\nMODELS = [f'/kaggle/input/birdclef-2025-sed-models-p/sed{i}.pth' for i in range(3)]\n\nMODELS","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.311410Z","iopub.execute_input":"2025-05-15T20:42:18.311807Z","iopub.status.idle":"2025-05-15T20:42:18.347599Z","shell.execute_reply.started":"2025-05-15T20:42:18.311773Z","shell.execute_reply":"2025-05-15T20:42:18.346005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"models = []\nfor path in MODELS:\n    model = TimmSED(base_model_name=base_model_name,\n               pretrained=pretrained,\n               num_classes=len(class_labels),\n               in_channels=in_channels,\n               n_mels=n_mels);\n    model.load_state_dict(torch.load(path, weights_only=True, map_location=torch.device('cpu')))\n    model.eval();\n    models.append(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:18.350166Z","iopub.execute_input":"2025-05-15T20:42:18.350699Z","iopub.status.idle":"2025-05-15T20:42:20.297179Z","shell.execute_reply.started":"2025-05-15T20:42:18.350665Z","shell.execute_reply":"2025-05-15T20:42:20.295876Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predict","metadata":{}},{"cell_type":"code","source":"def prediction(afile):    \n    global pred\n    path = test_audio_dir + afile + '.ogg'\n    with torch.inference_mode():\n        sig = audio_to_mel(path)\n        outputs = None\n        for model in models:\n            model.eval()\n            p = model(sig)\n            p = torch.sigmoid(p['logit']).detach().cpu().numpy() \n            p = apply_power_to_low_ranked_cols(p, top_k=30,exponent=2)\n            if outputs is None: outputs = p\n            else: outputs += p\n            \n        outputs /= len(models)\n        chunks = [[] for i in range(12)]\n        for i in range(len(chunks)):        \n            chunk_end_time = (i + 1) * 5\n            row_id = afile + '_' + str(chunk_end_time)\n            pred['row_id'].append(row_id)\n            bird_no = 0\n            for bird in class_labels:         \n                pred[bird].append(outputs[i,bird_no])\n                bird_no += 1\n        gc.collect()","metadata":{"papermill":{"duration":0.011209,"end_time":"2025-03-12T14:13:02.593243","exception":false,"start_time":"2025-03-12T14:13:02.582034","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:20.299187Z","iopub.execute_input":"2025-05-15T20:42:20.299546Z","iopub.status.idle":"2025-05-15T20:42:20.309401Z","shell.execute_reply.started":"2025-05-15T20:42:20.299517Z","shell.execute_reply":"2025-05-15T20:42:20.307286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred = {'row_id': []}\nfor species_code in class_labels:\n    pred[species_code] = []\n    \nstart = time.time()\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n    _ = list(executor.map(prediction, file_list))\nend_t = time.time()\n\nif debug == True:\n    print(700*(end_t - start)/60/debug_num)","metadata":{"papermill":{"duration":6.823541,"end_time":"2025-03-12T14:13:09.419521","exception":false,"start_time":"2025-03-12T14:13:02.59598","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:20.311995Z","iopub.execute_input":"2025-05-15T20:42:20.312851Z","iopub.status.idle":"2025-05-15T20:42:45.714310Z","shell.execute_reply.started":"2025-05-15T20:42:20.312791Z","shell.execute_reply":"2025-05-15T20:42:45.713155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = pd.DataFrame(pred, columns = ['row_id'] + class_labels) \ndisplay(results.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:45.715524Z","iopub.execute_input":"2025-05-15T20:42:45.715937Z","iopub.status.idle":"2025-05-15T20:42:45.764441Z","shell.execute_reply.started":"2025-05-15T20:42:45.715896Z","shell.execute_reply":"2025-05-15T20:42:45.763103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results.to_csv(\"submission.csv\", index=False)    \n\nsub = pd.read_csv('submission.csv')\ncols = sub.columns[1:]\ngroups = sub['row_id'].str.rsplit('_', n=1).str[0]\ngroups = groups.values\nfor group in np.unique(groups):\n    sub_group = sub[group == groups]\n    predictions = sub_group[cols].values\n    new_predictions = predictions.copy()\n    for i in range(1, predictions.shape[0]-1):\n        new_predictions[i] = (predictions[i-1] * 0.2) + (predictions[i] * 0.6) + (predictions[i+1] * 0.2)\n    new_predictions[0] = (predictions[0] * 0.8) + (predictions[1] * 0.2)\n    new_predictions[-1] = (predictions[-1] * 0.8) + (predictions[-2] * 0.2)\n    sub_group[cols] = new_predictions\n    sub[group == groups] = sub_group\nsub.to_csv(\"submission.csv\", index=False)\n\n\nif debug:\n    display(results)","metadata":{"papermill":{"duration":0.097214,"end_time":"2025-03-12T14:13:09.519812","exception":false,"start_time":"2025-03-12T14:13:09.422598","status":"completed"},"tags":[],"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:45.766003Z","iopub.execute_input":"2025-05-15T20:42:45.766380Z","iopub.status.idle":"2025-05-15T20:42:46.528426Z","shell.execute_reply.started":"2025-05-15T20:42:45.766349Z","shell.execute_reply":"2025-05-15T20:42:46.526629Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Sound Event Visualisations\n* Related Notebooks  \n[BirdCLEF2025+:Sound Event Visualisations](https://www.kaggle.com/code/myso1987/birdclef2025-sound-event-visualisations)","metadata":{}},{"cell_type":"code","source":"if debug == True:\n    import numpy as np\n    import matplotlib.pyplot as plt\n    \n    sample_rate = 32000\n    n_fft=1024\n    win_length=1024\n    hop_length=512\n    f_min=50\n    f_max=16000\n    n_mels=128\n    \n    mel_spectrogram = AT.MelSpectrogram(\n        sample_rate=sample_rate,\n        n_fft=n_fft,\n        win_length=win_length,\n        hop_length=hop_length,\n        center=True,\n        f_min=f_min,\n        f_max=f_max,\n        pad_mode=\"reflect\",\n        power=2.0,\n        norm='slaney',\n        n_mels=n_mels,\n        mel_scale=\"htk\",\n        # normalized=True\n    )\n    \n    def audio_to_mel_debug(filepath=None):\n        waveform, sample_rate = torchaudio.load(filepath,backend=\"soundfile\")\n        len_wav = waveform.shape[1]\n        waveform = waveform / torch.max(torch.abs(waveform))\n        melspec = mel_spectrogram(waveform)\n        melspec = 10*torch.log10(melspec)\n        return melspec\n    \n    def plot_results(results, file_name):\n        path = test_audio_dir + file_name + \".ogg\"\n        specgram = audio_to_mel_debug(path)\n        fig, axes = plt.subplots(2, 1, figsize=(10, 8))\n        axes[0].set_title(file_name)\n        im = axes[0].imshow((specgram[0]), origin=\"lower\", aspect=\"auto\")\n        axes[0].set_ylabel(\"mel bin\")\n        axes[0].set_xlabel(\"frame\")\n        fig.colorbar(im, ax=axes[0])\n        heatmap = axes[1].pcolor(results[results[\"row_id\"].str.contains(file_name)].iloc[:12,1:].values.T, edgecolors='k', linewidths=0.1, vmin=0, vmax=1, cmap='Blues')\n        fig.colorbar(heatmap, ax=axes[1])\n        axes[1].set_xticks(np.arange(0, 12, 1))\n        axes[1].set_xticklabels(np.arange(0,60,5))\n        axes[1].set_ylabel(\"sec\")\n        axes[1].set_xlabel(\"species\")\n        fig.tight_layout()\n        fig.show()\n        \n    for file_name in file_list:\n        plot_results(results, file_name)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-15T20:42:46.530025Z","iopub.execute_input":"2025-05-15T20:42:46.530485Z","iopub.status.idle":"2025-05-15T20:42:56.317874Z","shell.execute_reply.started":"2025-05-15T20:42:46.530429Z","shell.execute_reply":"2025-05-15T20:42:56.316071Z"}},"outputs":[],"execution_count":null}]}