{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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":"gpu","dataSources":[{"sourceId":91844,"databundleVersionId":11361821,"sourceType":"competition"},{"sourceId":11590046,"sourceType":"datasetVersion","datasetId":7267557}],"dockerImageVersionId":30918,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<h1 style=\"color: #6cb4e4;  text-align: center;  padding: 0.25em;  border-top: solid 2.5px #6cb4e4;  border-bottom: solid 2.5px #6cb4e4;  background: -webkit-repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);  background: repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);height:45px;\">\n<b>\nOnly Submission(LoadLocalTrainModel)\n</b></h1> ","metadata":{}},{"cell_type":"markdown","source":"### **ℹ️INFO**\n* This notebook is an inference notebook.\n* that performed a unique LocalTrain based on the great Train/Inference published by the Kadircan İdrisoğlu.\n    * [PP] https://www.kaggle.com/code/kadircandrisolu/transforming-audio-to-mel-spec-birdclef-25\n    * [TRAIN] https://www.kaggle.com/code/kadircandrisolu/efficientnet-b0-pytorch-train-birdclef-25\n    * [INF] https://www.kaggle.com/code/kadircandrisolu/efficientnet-b0-pytorch-inference-birdclef-25\n\n### **ℹ️2025/04/28 MyLocalTrainResult**\n* trained using FocalLossBCE, which was used in the previous competition, BirdCLEF 2024 8th place solution. The results were good.\n    ```\n    0.9652\n    0.9605\n    0.9607\n    0.9626\n    [OOF]0.9622\n    ```","metadata":{}},{"cell_type":"code","source":"import os\nimport gc\nimport warnings\nimport logging\nimport time\nimport math\nimport cv2\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport timm\nfrom tqdm.auto import tqdm\nimport torchvision\nwarnings.filterwarnings(\"ignore\")\nlogging.basicConfig(level=logging.ERROR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.278534Z","iopub.execute_input":"2025-04-27T17:09:17.278855Z","iopub.status.idle":"2025-04-27T17:09:17.284752Z","shell.execute_reply.started":"2025-04-27T17:09:17.278834Z","shell.execute_reply":"2025-04-27T17:09:17.283591Z"},"_kg_hide-input":true,"_kg_hide-output":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"\"\" \n    FocalLossBCE Use Example\n\"\"\"\nclass FocalLossBCE(torch.nn.Module):\n    def __init__(\n            self,\n            alpha: float = 0.25,\n            gamma: float = 2,\n            reduction: str = \"mean\",\n            bce_weight: float = 0.6,\n            focal_weight: float = 1.4,\n    ):\n        super().__init__()\n        self.alpha = alpha\n        self.gamma = gamma\n        self.reduction = reduction\n        self.bce = torch.nn.BCEWithLogitsLoss(reduction=reduction)\n        self.bce_weight = bce_weight\n        self.focal_weight = focal_weight\n\n    def forward(self, logits, targets):\n        focall_loss = torchvision.ops.focal_loss.sigmoid_focal_loss(\n            inputs=logits,\n            targets=targets,\n            alpha=self.alpha,\n            gamma=self.gamma,\n            reduction=self.reduction,\n        )\n        bce_loss = self.bce(logits, targets)\n        return self.bce_weight * bce_loss + self.focal_weight * focall_loss\n\ndef get_criterion(cfg):\n    return FocalLossBCE()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.286045Z","iopub.execute_input":"2025-04-27T17:09:17.286492Z","iopub.status.idle":"2025-04-27T17:09:17.3076Z","shell.execute_reply.started":"2025-04-27T17:09:17.286433Z","shell.execute_reply":"2025-04-27T17:09:17.306324Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<h1 style=\"color: #6cb4e4;  text-align: center;  padding: 0.25em;  border-top: solid 2.5px #6cb4e4;  border-bottom: solid 2.5px #6cb4e4;  background: -webkit-repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);  background: repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);height:45px;\">\n<b>\nInference Pipeline\n</b></h1> ","metadata":{}},{"cell_type":"markdown","source":"## **》》》Env**","metadata":{}},{"cell_type":"code","source":"class CFG:\n    # ------------------------------------------- #\n    # [IMPORTANT]\n    # * Melspectrogram & Audio Params\n    # ------------------------------------------- #\n    N_FFT = 2048\n    HOP_LENGTH = 128\n    N_MELS = 512\n    FMIN = 20\n    FMAX = 16000\n    TARGET_SHAPE = (256, 256)\n    FS = 32000  \n    WINDOW_SIZE = 5\n\n    # ------------------------------------------- #\n    # * Model def\n    # ------------------------------------------- #\n    model_path = '/kaggle/input/pub-bird25-b-422-ppv15-v2-s-focallossbce'\n    model_name = 'tf_efficientnetv2_s.in21k_ft_in1k'\n    use_specific_folds = False\n    folds = [0,1,2,3]\n    in_channels = 1\n    #device = 'cpu'  \n    device = 'cuda'          # 若使用 Kaggle P100/V100\n    use_half = True\n    # datasets\n    test_soundscapes = '/kaggle/input/birdclef-2025/test_soundscapes'\n    submission_csv = '/kaggle/input/birdclef-2025/sample_submission.csv'\n    taxonomy_csv = '/kaggle/input/birdclef-2025/taxonomy.csv'\n    \n    # Inference parameters\n    batch_size = 16\n    use_tta = False  \n    tta_count = 3\n    threshold = 0.5\n\n    # util\n    debug = False\n    debug_count = 3\n\ncfg = CFG()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.382163Z","iopub.execute_input":"2025-04-27T17:09:17.382583Z","iopub.status.idle":"2025-04-27T17:09:17.388961Z","shell.execute_reply.started":"2025-04-27T17:09:17.382553Z","shell.execute_reply":"2025-04-27T17:09:17.387715Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Using device: {cfg.device}\")\nprint(f\"Loading taxonomy data...\")\ntaxonomy_df = pd.read_csv(cfg.taxonomy_csv)\nspecies_ids = taxonomy_df['primary_label'].tolist()\nnum_classes = len(species_ids)\nprint(f\"Number of classes: {num_classes}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.455324Z","iopub.execute_input":"2025-04-27T17:09:17.455731Z","iopub.status.idle":"2025-04-27T17:09:17.466084Z","shell.execute_reply.started":"2025-04-27T17:09:17.455703Z","shell.execute_reply":"2025-04-27T17:09:17.464748Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》Model**","metadata":{}},{"cell_type":"code","source":"class GeM(nn.Module):\n    def __init__(self, p=3.0, eps=1e-6):\n        super().__init__()\n        self.p = nn.Parameter(torch.ones(1) * p)\n        self.eps = eps\n    def forward(self, x):\n        return F.avg_pool2d(x.clamp(min=self.eps).pow(self.p),\n                            (x.size(-2), x.size(-1))).pow(1./self.p)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class BirdCLEFModel(nn.Module):\n    def __init__(self, cfg, num_classes):\n        super().__init__()\n        self.cfg = cfg\n        \n        self.backbone = timm.create_model(\n            cfg.model_name,\n            pretrained=False,  \n            in_chans=cfg.in_channels,\n            drop_rate=0.0,    \n            drop_path_rate=0.0\n        )\n        \n        backbone_out = self.backbone.classifier.in_features\n        self.backbone.classifier = nn.Identity()\n        #self.pooling = nn.AdaptiveAvgPool2d(1)\n        self.pooling = GeM()\n        self.feat_dim = backbone_out\n        self.classifier = nn.Linear(backbone_out, num_classes)\n        \n    def forward(self, x):\n        features = self.backbone(x)\n        if isinstance(features, dict):\n            features = features['features']\n        if len(features.shape) == 4:\n            features = self.pooling(features)\n            features = features.view(features.size(0), -1)\n\n        logits = self.classifier(features)\n        return logits","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.589972Z","iopub.execute_input":"2025-04-27T17:09:17.590395Z","iopub.status.idle":"2025-04-27T17:09:17.599731Z","shell.execute_reply.started":"2025-04-27T17:09:17.590361Z","shell.execute_reply":"2025-04-27T17:09:17.59811Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》Melspectrogram**","metadata":{}},{"cell_type":"code","source":"def audio2melspec(audio_data, cfg):\n    \"\"\"Convert audio data to mel spectrogram\"\"\"\n    if np.isnan(audio_data).any():\n        mean_signal = np.nanmean(audio_data)\n        audio_data = np.nan_to_num(audio_data, nan=mean_signal)\n\n    mel_spec = librosa.feature.melspectrogram(\n        y=audio_data,\n        sr=cfg.FS,\n        n_fft=cfg.N_FFT,\n        hop_length=cfg.HOP_LENGTH,\n        n_mels=cfg.N_MELS,\n        fmin=cfg.FMIN,\n        fmax=cfg.FMAX,\n        power=2.0,\n        pad_mode=\"reflect\",\n        norm='slaney',\n        htk=True,\n        center=True,\n    )\n\n    mel_spec_db = librosa.power_to_db(mel_spec, ref=np.max)\n    mel_spec_norm = (mel_spec_db - mel_spec_db.min()) / (mel_spec_db.max() - mel_spec_db.min() + 1e-8)\n    \n    return mel_spec_norm\n\ndef process_audio_segment(audio_data, cfg):\n    \"\"\"Process audio segment to get mel spectrogram\"\"\"\n    if len(audio_data) < cfg.FS * cfg.WINDOW_SIZE:\n        audio_data = np.pad(audio_data, \n                          (0, cfg.FS * cfg.WINDOW_SIZE - len(audio_data)), \n                          mode='constant')\n    \n    mel_spec = audio2melspec(audio_data, cfg)\n    \n    if mel_spec.shape != cfg.TARGET_SHAPE:\n        mel_spec = cv2.resize(mel_spec, cfg.TARGET_SHAPE, interpolation=cv2.INTER_LINEAR)\n        \n    return mel_spec.astype(np.float32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.683758Z","iopub.execute_input":"2025-04-27T17:09:17.684109Z","iopub.status.idle":"2025-04-27T17:09:17.692085Z","shell.execute_reply.started":"2025-04-27T17:09:17.684084Z","shell.execute_reply":"2025-04-27T17:09:17.690941Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------------------------------------------------------------------\n# 1. 找模型文件\n# ----------------------------------------------------------------------\ndef find_model_files(cfg):\n    \"\"\"\n    Find all .pth model files in the specified model directory\n    \"\"\"\n    model_files = []\n    model_dir = Path(cfg.model_path)\n\n    for path in model_dir.glob('**/*.pth'):\n        model_files.append(str(path))\n\n    return model_files\n\n\n# ----------------------------------------------------------------------\n# 2. 加载模型（支持 fp16 / cuda）\n# ----------------------------------------------------------------------\ndef load_models(cfg, num_classes):\n    \"\"\"\n    Load all found model files and prepare them for ensemble\n    \"\"\"\n    models = []\n\n    model_files = find_model_files(cfg)\n    if not model_files:\n        print(f\"Warning: No model files found under {cfg.model_path}!\")\n        return models\n\n    print(f\"Found a total of {len(model_files)} model files.\")\n\n    if cfg.use_specific_folds:\n        filtered_files = []\n        for fold in cfg.folds:\n            fold_files = [f for f in model_files if f\"fold{fold}\" in f]\n            filtered_files.extend(fold_files)\n        model_files = filtered_files\n        print(f\"Using {len(model_files)} model files for the specified folds ({cfg.folds}).\")\n\n    for model_path in model_files:\n        try:\n            print(f\"Loading model: {model_path}\")\n            checkpoint = torch.load(model_path, map_location=torch.device(cfg.device))\n\n            model = BirdCLEFModel(cfg, num_classes)\n            model.load_state_dict(checkpoint['model_state_dict'])\n            model = model.to(cfg.device)\n            if getattr(cfg, \"use_half\", False):\n                model = model.half()\n            model.eval()\n\n            models.append(model)\n        except Exception as e:\n            print(f\"Error loading model {model_path}: {e}\")\n\n    return models\n\n\n# ----------------------------------------------------------------------\n# 3. 单文件推断（两处张量转 fp16/cuda 已修正）\n# ----------------------------------------------------------------------\ndef predict_on_spectrogram(audio_path, models, cfg, species_ids):\n    \"\"\"Process a single audio file and predict species presence for each 5‑second segment\"\"\"\n    predictions = []\n    row_ids = []\n    soundscape_id = Path(audio_path).stem\n\n    try:\n        print(f\"Processing {soundscape_id}\")\n        audio_data, _ = librosa.load(audio_path, sr=cfg.FS)\n\n        total_segments = int(len(audio_data) / (cfg.FS * cfg.WINDOW_SIZE))\n\n        for segment_idx in range(total_segments):\n            start_sample = segment_idx * cfg.FS * cfg.WINDOW_SIZE\n            end_sample = start_sample + cfg.FS * cfg.WINDOW_SIZE\n            segment_audio = audio_data[start_sample:end_sample]\n\n            end_time_sec = (segment_idx + 1) * cfg.WINDOW_SIZE\n            row_id = f\"{soundscape_id}_{end_time_sec}\"\n            row_ids.append(row_id)\n\n            # ----------------------------------------------------------\n            # 3‑a. TTA 分支\n            # ----------------------------------------------------------\n            if cfg.use_tta:\n                all_preds = []\n\n                for tta_idx in range(cfg.tta_count):\n                    mel_spec = process_audio_segment(segment_audio, cfg)\n                    mel_spec = apply_tta(mel_spec, tta_idx)\n\n                    mel_spec = torch.tensor(\n                        mel_spec,\n                        dtype=torch.float16 if getattr(cfg, \"use_half\", False) else torch.float32\n                    ).unsqueeze(0).unsqueeze(0).to(cfg.device)\n\n                    if len(models) == 1:\n                        with torch.no_grad():\n                            outputs = models[0](mel_spec)\n                            probs = torch.sigmoid(outputs).cpu().numpy().squeeze()\n                            all_preds.append(probs)\n                    else:\n                        segment_preds = []\n                        for model in models:\n                            with torch.no_grad():\n                                outputs = model(mel_spec)\n                                probs = torch.sigmoid(outputs).cpu().numpy().squeeze()\n                                segment_preds.append(probs)\n                        avg_preds = np.mean(segment_preds, axis=0)\n                        all_preds.append(avg_preds)\n\n                final_preds = np.mean(all_preds, axis=0)\n\n            # ----------------------------------------------------------\n            # 3‑b. 无 TTA 分支\n            # ----------------------------------------------------------\n            else:\n                mel_spec = process_audio_segment(segment_audio, cfg)\n\n                mel_spec = torch.tensor(\n                    mel_spec,\n                    dtype=torch.float16 if getattr(cfg, \"use_half\", False) else torch.float32\n                ).unsqueeze(0).unsqueeze(0).to(cfg.device)\n\n                if len(models) == 1:\n                    with torch.no_grad():\n                        outputs = models[0](mel_spec)\n                        final_preds = torch.sigmoid(outputs).cpu().numpy().squeeze()\n                else:\n                    segment_preds = []\n                    for model in models:\n                        with torch.no_grad():\n                            outputs = model(mel_spec)\n                            probs = torch.sigmoid(outputs).cpu().numpy().squeeze()\n                            segment_preds.append(probs)\n                    final_preds = np.mean(segment_preds, axis=0)\n\n            predictions.append(final_preds)\n\n    except Exception as e:\n        print(f\"Error processing {audio_path}: {e}\")\n\n    return row_ids, predictions\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.716518Z","iopub.execute_input":"2025-04-27T17:09:17.716896Z","iopub.status.idle":"2025-04-27T17:09:17.733391Z","shell.execute_reply.started":"2025-04-27T17:09:17.716867Z","shell.execute_reply":"2025-04-27T17:09:17.732184Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def apply_tta(spec, tta_idx):\n    \"\"\"Apply test-time augmentation\"\"\"\n    if tta_idx == 0:\n        # Original spectrogram\n        return spec\n    elif tta_idx == 1:\n        # Time shift (horizontal flip)\n        return np.flip(spec, axis=1)\n    elif tta_idx == 2:\n        # Frequency shift (vertical flip)\n        return np.flip(spec, axis=0)\n    else:\n        return spec\n\ndef run_inference(cfg, models, species_ids):\n    \"\"\"Run inference on all test soundscapes\"\"\"\n    test_files = list(Path(cfg.test_soundscapes).glob('*.ogg'))\n    \n    if cfg.debug:\n        print(f\"Debug mode enabled, using only {cfg.debug_count} files\")\n        test_files = test_files[:cfg.debug_count]\n    \n    print(f\"Found {len(test_files)} test soundscapes\")\n\n    all_row_ids = []\n    all_predictions = []\n\n    for audio_path in tqdm(test_files):\n        row_ids, predictions = predict_on_spectrogram(str(audio_path), models, cfg, species_ids)\n        all_row_ids.extend(row_ids)\n        all_predictions.extend(predictions)\n    \n    return all_row_ids, all_predictions\n\ndef create_submission(row_ids, predictions, species_ids, cfg):\n    \"\"\"Create submission dataframe\"\"\"\n    print(\"Creating submission dataframe...\")\n\n    submission_dict = {'row_id': row_ids}\n    \n    for i, species in enumerate(species_ids):\n        submission_dict[species] = [pred[i] for pred in predictions]\n\n    submission_df = pd.DataFrame(submission_dict)\n    submission_df.set_index('row_id', inplace=True)\n    sample_sub = pd.read_csv(cfg.submission_csv, index_col='row_id')\n\n    missing_cols = set(sample_sub.columns) - set(submission_df.columns)\n    if missing_cols:\n        print(f\"Warning: Missing {len(missing_cols)} species columns in submission\")\n        for col in missing_cols:\n            submission_df[col] = 0.0\n\n    submission_df = submission_df[sample_sub.columns]\n    submission_df = submission_df.reset_index()\n    \n    return submission_df\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.784726Z","iopub.execute_input":"2025-04-27T17:09:17.785058Z","iopub.status.idle":"2025-04-27T17:09:17.795122Z","shell.execute_reply.started":"2025-04-27T17:09:17.785034Z","shell.execute_reply":"2025-04-27T17:09:17.793636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def main():\n    start_time = time.time()\n    print(\"Starting BirdCLEF-2025 inference...\")\n    print(f\"TTA enabled: {cfg.use_tta} (variations: {cfg.tta_count if cfg.use_tta else 0})\")\n\n    models = load_models(cfg, num_classes)\n    \n    if not models:\n        print(\"No models found! Please check model paths.\")\n        return\n    \n    print(f\"Model usage: {'Single model' if len(models) == 1 else f'Ensemble of {len(models)} models'}\")\n\n    row_ids, predictions = run_inference(cfg, models, species_ids)\n    submission_df = create_submission(row_ids, predictions, species_ids, cfg)\n    submission_path = 'submission.csv'\n    submission_df.to_csv(submission_path, index=False)\n    print(f\"Submission saved to {submission_path}\")\n    \n    end_time = time.time()\n    print(f\"Inference completed in {(end_time - start_time)/60:.2f} minutes\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.849018Z","iopub.execute_input":"2025-04-27T17:09:17.849373Z","iopub.status.idle":"2025-04-27T17:09:17.855631Z","shell.execute_reply.started":"2025-04-27T17:09:17.849346Z","shell.execute_reply":"2025-04-27T17:09:17.85448Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<h1 style=\"color: #6cb4e4;  text-align: center;  padding: 0.25em;  border-top: solid 2.5px #6cb4e4;  border-bottom: solid 2.5px #6cb4e4;  background: -webkit-repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);  background: repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);height:45px;\">\n<b>\nCreate Submission\n</b></h1> ","metadata":{}},{"cell_type":"code","source":"if __name__ == \"__main__\":\n    main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:17.926724Z","iopub.execute_input":"2025-04-27T17:09:17.927065Z","iopub.status.idle":"2025-04-27T17:09:28.988014Z","shell.execute_reply.started":"2025-04-27T17:09:17.927037Z","shell.execute_reply":"2025-04-27T17:09:28.986882Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub = 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.9) + (predictions[1] * 0.1)\n    new_predictions[-1] = (predictions[-1] * 0.9) + (predictions[-2] * 0.1)\n    sub_group[cols] = new_predictions\n    sub[group == groups] = sub_group\nsub.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-27T17:09:28.989712Z","iopub.execute_input":"2025-04-27T17:09:28.990013Z","iopub.status.idle":"2025-04-27T17:09:29.021657Z","shell.execute_reply.started":"2025-04-27T17:09:28.989989Z","shell.execute_reply":"2025-04-27T17:09:29.02054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}