{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":91844,"databundleVersionId":11361821,"sourceType":"competition"},{"sourceId":11053663,"sourceType":"datasetVersion","datasetId":6886569},{"sourceId":11795685,"sourceType":"datasetVersion","datasetId":7397754},{"sourceId":11795745,"sourceType":"datasetVersion","datasetId":7407139}],"dockerImageVersionId":30919,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **BirdCLEF 2025 Training Notebook**\n\nThis is a baseline training pipeline for BirdCLEF 2025 using EfficientNetB0 with PyTorch and Timm(for pretrained EffNet). You can check inference and preprocessing notebooks in the following links: \n\n- [EfficientNet B0 Pytorch [Inference] | BirdCLEF'25](https://www.kaggle.com/code/kadircandrisolu/efficientnet-b0-pytorch-inference-birdclef-25)\n\n  \n- [Transforming Audio-to-Mel Spec. | BirdCLEF'25](https://www.kaggle.com/code/kadircandrisolu/transforming-audio-to-mel-spec-birdclef-25)  \n\nNote that by default this notebook is in Debug Mode, so it will only train the model with 2 epochs, but the [weight](https://www.kaggle.com/datasets/kadircandrisolu/birdclef25-effnetb0-starter-weight) I used in the inference notebook was obtained after 10 epochs of training.\n\n**Features**\n* Implement with Pytorch and Timm\n* Flexible audio processing with both pre-computed and on-the-fly mel spectrograms\n* Stratified 5-fold cross-validation with ensemble capability\n* Mixup training for improved generalization\n* Spectrogram augmentations (time/frequency masking, brightness adjustment)\n* AdamW optimizer with Cosine Annealing LR scheduling\n* Debug mode for quick experimentation with smaller datasets\n\n**Pre-computed Spectrograms**\nFor faster training, you can use pre-computed mel spectrograms from [this dataset](https://www.kaggle.com/datasets/kadircandrisolu/birdclef25-mel-spectrograms) by setting `LOAD_DATA = True`","metadata":{}},{"cell_type":"markdown","source":"## Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport logging\nimport random\nimport gc\nimport time\nimport cv2\nimport math\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_auc_score\nimport librosa\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm.auto import tqdm\n\nimport timm\n\nwarnings.filterwarnings(\"ignore\")\nlogging.basicConfig(level=logging.ERROR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:22:45.653733Z","iopub.execute_input":"2025-06-05T12:22:45.653998Z","iopub.status.idle":"2025-06-05T12:23:07.052638Z","shell.execute_reply.started":"2025-06-05T12:22:45.653974Z","shell.execute_reply":"2025-06-05T12:23:07.051932Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Configuration","metadata":{}},{"cell_type":"code","source":"class CFG:\n    \n    seed = 42\n    debug = False  \n    apex = False\n    print_freq = 100\n    num_workers = 2\n    \n    OUTPUT_DIR = '/kaggle/working/'\n\n    train_datadir = '/kaggle/input/birdclef-2025/train_audio'\n    train_csv = '/kaggle/input/birdclef-2025/train.csv'\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    spectrogram_npy = ['/kaggle/input/birdclef25-mel-spectrograms/birdclef2025_melspec_5sec_256_256.npy','/kaggle/input/last-melspec-5sec/0513_melspec_last5sec.npy'] \n \n    model_name = 'efficientnet_b0'  \n    pretrained = True\n    in_channels = 1\n\n    LOAD_DATA = True  \n    FS = 32000\n    TARGET_DURATION = 5.0\n    TARGET_SHAPE = (256, 256)\n    \n    N_FFT = 1024\n    HOP_LENGTH = 512\n    N_MELS = 128\n    FMIN = 50\n    FMAX = 14000\n    \n    device = 'cuda' if torch.cuda.is_available() else 'cpu'\n    epochs = 10  \n    batch_size = 32  \n    criterion = 'BCEWithLogitsLoss'\n\n    n_fold = 5\n    selected_folds = [0,1,2,3,4]   \n\n    optimizer = 'AdamW'\n    lr = 5e-4 \n    weight_decay = 1e-5\n\n    aug_prob = 0.5  \n    mixup_alpha = 0.5  \n    \n    scheduler = 'OneCycleLR'  # 设置为 OneCycleLR\n    lr = 5e-4  # 最大学习率\n    T_max = 10  # 一个完整周期的总迭代次数（可以根据需要调整）\n    pct_start = 0.3  # 学习率增长阶段占总迭代次数的比例\n    div_factor = 25.0  # 最大学习率与初始学习率的比值\n    final_div_factor = 10000.0  # 最大学习率与最终学习率的比值\n    \n    def update_debug_settings(self):\n        if self.debug:\n            self.epochs = 2\n            self.selected_folds = [0, 1]\n\ncfg = CFG()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:25:58.019273Z","iopub.execute_input":"2025-06-05T12:25:58.019693Z","iopub.status.idle":"2025-06-05T12:25:58.111997Z","shell.execute_reply.started":"2025-06-05T12:25:58.019649Z","shell.execute_reply":"2025-06-05T12:25:58.111094Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Utilities","metadata":{}},{"cell_type":"code","source":"def set_seed(seed=42):\n    \"\"\"\n    Set seed for reproducibility\n    \"\"\"\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\nset_seed(cfg.seed)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:00.383097Z","iopub.execute_input":"2025-06-05T12:26:00.383390Z","iopub.status.idle":"2025-06-05T12:26:00.397306Z","shell.execute_reply.started":"2025-06-05T12:26:00.383366Z","shell.execute_reply":"2025-06-05T12:26:00.396528Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Pre-processing\nThese functions handle the transformation of audio files to mel spectrograms for model input, with flexibility controlled by the `LOAD_DATA` parameter. The process involves either loading pre-computed spectrograms from this [dataset](https://www.kaggle.com/datasets/kadircandrisolu/birdclef25-mel-spectrograms) (when `LOAD_DATA=True`) or dynamically generating them (when `LOAD_DATA=False`), transforming audio data into spectrogram representations, and preparing it for the neural network.","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    )\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_file(audio_path, cfg):\n    \"\"\"Process a single audio file to get the mel spectrogram\"\"\"\n    try:\n        audio_data, _ = librosa.load(audio_path, sr=cfg.FS)\n\n        target_samples = int(cfg.TARGET_DURATION * cfg.FS)  # 10 seconds\n\n        # Extract the middle 10 seconds (5 seconds before and 5 seconds after the center)\n        total_length = len(audio_data)\n        center_sample = total_length // 2\n\n        # Extract the 5 seconds before the center\n        start_idx = max(0, center_sample - int(5 * cfg.FS))\n        end_idx = min(total_length, center_sample)\n        before_center_audio = audio_data[start_idx:end_idx]\n\n        # Extract the 5 seconds after the center\n        start_idx = center_sample\n        end_idx = min(total_length, center_sample + int(5 * cfg.FS))\n        after_center_audio = audio_data[start_idx:end_idx]\n\n        # Combine the two segments\n        combined_audio = np.concatenate([before_center_audio, after_center_audio])\n\n        # If the combined audio is shorter than the target duration, pad it\n        if len(combined_audio) < target_samples:\n            combined_audio = np.pad(combined_audio, \n                                    (0, target_samples - len(combined_audio)), \n                                    mode='constant')\n\n        # If the combined audio is longer than the target duration, truncate it\n        if len(combined_audio) > target_samples:\n            combined_audio = combined_audio[:target_samples]\n\n        mel_spec = audio2melspec(combined_audio, 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)\n        \n    except Exception as e:\n        print(f\"Error processing {audio_path}: {e}\")\n        return None\n\ndef generate_spectrograms(df, cfg):\n    \"\"\"Generate spectrograms from audio files\"\"\"\n    print(\"Generating mel spectrograms from audio files...\")\n    start_time = time.time()\n\n    all_bird_data = {}\n    errors = []\n\n    for i, row in tqdm(df.iterrows(), total=len(df)):\n        if cfg.debug and i >= 1000:\n            break\n        \n        try:\n            samplename = row['samplename']\n            filepath = row['filepath']\n            \n            mel_spec = process_audio_file(filepath, cfg)\n            \n            if mel_spec is not None:\n                all_bird_data[samplename] = mel_spec\n            \n        except Exception as e:\n            print(f\"Error processing {row.filepath}: {e}\")\n            errors.append((row.filepath, str(e)))\n\n    end_time = time.time()\n    print(f\"Processing completed in {end_time - start_time:.2f} seconds\")\n    print(f\"Successfully processed {len(all_bird_data)} files out of {len(df)}\")\n    print(f\"Failed to process {len(errors)} files\")\n    \n    # 加载额外的数据集\n    for npy_file in cfg.spectrogram_npy:\n        try:\n            additional_spectrograms = np.load(npy_file, allow_pickle=True).item()\n            print(f\"Loaded {len(additional_spectrograms)} pre-computed mel spectrograms from {npy_file}\")\n            all_bird_data.update(additional_spectrograms)\n        except Exception as e:\n            print(f\"Error loading pre-computed spectrograms from {npy_file}: {e}\")\n    \n    return all_bird_data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:02.486579Z","iopub.execute_input":"2025-06-05T12:26:02.486882Z","iopub.status.idle":"2025-06-05T12:26:02.498482Z","shell.execute_reply.started":"2025-06-05T12:26:02.486859Z","shell.execute_reply":"2025-06-05T12:26:02.497595Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Dataset Preparation and Data Augmentations\nWe'll convert audio to mel spectrograms and apply random augmentations with 50% probability each - including time stretching, pitch shifting, and volume adjustments. This randomized approach creates diverse training samples from the same audio files","metadata":{}},{"cell_type":"code","source":"class BirdCLEFDatasetFromNPY(Dataset):\n    def __init__(self, df, cfg, spectrograms=None, mode=\"train\"):\n        \"\"\"\n        Dataset class for loading mel spectrograms from pre-computed NPY files or generating them on-the-fly.\n\n        Args:\n            df (pd.DataFrame): DataFrame containing the training or validation data.\n            cfg (CFG): Configuration object containing various settings.\n            spectrograms (dict, optional): Pre-computed spectrograms loaded from NPY files. Defaults to None.\n            mode (str, optional): Mode of the dataset ('train' or 'valid'). Defaults to \"train\".\n        \"\"\"\n        self.df = df\n        self.cfg = cfg\n        self.mode = mode\n\n        # Initialize the spectrograms dictionary\n        self.spectrograms = spectrograms if spectrograms else {}\n\n        # Load taxonomy information\n        taxonomy_df = pd.read_csv(self.cfg.taxonomy_csv)\n        self.species_ids = taxonomy_df['primary_label'].tolist()\n        self.num_classes = len(self.species_ids)\n        self.label_to_idx = {label: idx for idx, label in enumerate(self.species_ids)}\n\n        # Prepare file paths and sample names\n        if 'filepath' not in self.df.columns:\n            self.df['filepath'] = self.cfg.train_datadir + '/' + self.df.filename\n        if 'samplename' not in self.df.columns:\n            self.df['samplename'] = self.df.filename.map(lambda x: x.split('/')[0] + '-' + x.split('/')[-1].split('.')[0])\n\n        # Check how many samples have matching spectrograms\n        sample_names = set(self.df['samplename'])\n        found_samples = {name: False for name in sample_names}\n\n        # Load pre-computed spectrograms from multiple NPY files\n        if self.spectrograms:\n            for npy_file in self.cfg.spectrogram_npy:\n                try:\n                    additional_spectrograms = np.load(npy_file, allow_pickle=True).item()\n                    print(f\"Loaded {len(additional_spectrograms)} pre-computed mel spectrograms from {npy_file}\")\n                    self.spectrograms.update(additional_spectrograms)\n                    for name in sample_names:\n                        if name in additional_spectrograms:\n                            found_samples[name] = True\n                except Exception as e:\n                    print(f\"Error loading pre-computed spectrograms from {npy_file}: {e}\")\n\n        # Check if all samples have matching spectrograms\n        all_loaded = all(found_samples.values())\n        if all_loaded:\n            print(f\"Success: All {len(self.df)} samples have matching spectrograms for {mode} dataset.\")\n        else:\n            found_count = sum(1 for name in found_samples if found_samples[name])\n            print(f\"Warning: Only {found_count} out of {len(self.df)} samples have matching spectrograms for {mode} dataset.\")\n\n        # Debug mode: limit the dataset size\n        if cfg.debug:\n            self.df = self.df.sample(min(1000, len(self.df)), random_state=cfg.seed).reset_index(drop=True)\n\n    def __len__(self):\n        \"\"\"Return the number of samples in the dataset.\"\"\"\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        \"\"\"\n        Get a single item from the dataset.\n\n        Args:\n            idx (int): Index of the item.\n\n        Returns:\n            dict: Dictionary containing the mel spectrogram, target label, and filename.\n        \"\"\"\n        row = self.df.iloc[idx]\n        samplename = row['samplename']\n        spec = None\n\n        # Try to load the spectrogram from the pre-computed dictionary\n        if self.spectrograms and samplename in self.spectrograms:\n            spec = self.spectrograms[samplename]\n        # If not available, generate the spectrogram on-the-fly\n        elif not self.cfg.LOAD_DATA:\n            spec = process_audio_file(row['filepath'], self.cfg)\n\n        # If spectrogram is still None, create a dummy spectrogram and print a warning\n        if spec is None:\n            spec = np.zeros(self.cfg.TARGET_SHAPE, dtype=np.float32)\n            if self.mode == \"train\":  # Only print warning during training\n                print(f\"Warning: Spectrogram for {samplename} not found and could not be generated\")\n\n        # Convert the spectrogram to a PyTorch tensor and add a channel dimension\n        spec = torch.tensor(spec, dtype=torch.float32).unsqueeze(0)\n\n        # Apply data augmentation if in training mode\n        if self.mode == \"train\" and random.random() < self.cfg.aug_prob:\n            spec = self.apply_spec_augmentations(spec)\n\n        # Encode the target label\n        target = self.encode_label(row['primary_label'])\n\n        # Handle secondary labels if available\n        if 'secondary_labels' in row and row['secondary_labels'] not in [[''], None, np.nan]:\n            if isinstance(row['secondary_labels'], str):\n                secondary_labels = eval(row['secondary_labels'])\n            else:\n                secondary_labels = row['secondary_labels']\n\n            for label in secondary_labels:\n                if label in self.label_to_idx:\n                    target[self.label_to_idx[label]] = 1.0\n\n        return {\n            'melspec': spec,\n            'target': torch.tensor(target, dtype=torch.float32),\n            'filename': row['filename']\n        }\n\n    def apply_spec_augmentations(self, spec):\n        \"\"\"\n        Apply augmentations to the spectrogram.\n\n        Args:\n            spec (torch.Tensor): Input spectrogram.\n\n        Returns:\n            torch.Tensor: Augmented spectrogram.\n        \"\"\"\n        # Time masking (horizontal stripes)\n        if random.random() < 0.5:\n            num_masks = random.randint(1, 3)\n            for _ in range(num_masks):\n                width = random.randint(5, 20)\n                start = random.randint(0, spec.shape[2] - width)\n                spec[0, :, start:start + width] = 0\n\n        # Frequency masking (vertical stripes)\n        if random.random() < 0.5:\n            num_masks = random.randint(1, 3)\n            for _ in range(num_masks):\n                height = random.randint(5, 20)\n                start = random.randint(0, spec.shape[1] - height)\n                spec[0, start:start + height, :] = 0\n\n        # Random brightness/contrast\n        if random.random() < 0.5:\n            gain = random.uniform(0.8, 1.2)\n            bias = random.uniform(-0.1, 0.1)\n            spec = spec * gain + bias\n            spec = torch.clamp(spec, 0, 1)\n\n        return spec\n\n    def encode_label(self, label):\n        \"\"\"\n        Encode the label to a one-hot vector.\n\n        Args:\n            label (str): Primary label.\n\n        Returns:\n            np.ndarray: One-hot encoded label.\n        \"\"\"\n        target = np.zeros(self.num_classes)\n        if label in self.label_to_idx:\n            target[self.label_to_idx[label]] = 1.0\n        return target","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:06.326819Z","iopub.execute_input":"2025-06-05T12:26:06.327118Z","iopub.status.idle":"2025-06-05T12:26:06.344522Z","shell.execute_reply.started":"2025-06-05T12:26:06.327095Z","shell.execute_reply":"2025-06-05T12:26:06.343513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def collate_fn(batch):\n    \"\"\"Custom collate function to handle different sized spectrograms\"\"\"\n    batch = [item for item in batch if item is not None]\n    if len(batch) == 0:\n        return {}\n        \n    result = {key: [] for key in batch[0].keys()}\n    \n    for item in batch:\n        for key, value in item.items():\n            result[key].append(value)\n    \n    for key in result:\n        if key == 'target' and isinstance(result[key][0], torch.Tensor):\n            result[key] = torch.stack(result[key])\n        elif key == 'melspec' and isinstance(result[key][0], torch.Tensor):\n            shapes = [t.shape for t in result[key]]\n            if len(set(str(s) for s in shapes)) == 1:\n                result[key] = torch.stack(result[key])\n    \n    return result","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:15.881458Z","iopub.execute_input":"2025-06-05T12:26:15.881767Z","iopub.status.idle":"2025-06-05T12:26:15.887380Z","shell.execute_reply.started":"2025-06-05T12:26:15.881747Z","shell.execute_reply":"2025-06-05T12:26:15.886621Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Model Definition","metadata":{}},{"cell_type":"code","source":"class BirdCLEFModel(nn.Module):\n    def __init__(self, cfg):\n        super().__init__()\n        self.cfg = cfg\n        \n        taxonomy_df = pd.read_csv(cfg.taxonomy_csv)\n        cfg.num_classes = len(taxonomy_df)\n        \n        self.backbone = timm.create_model(\n            cfg.model_name,\n            pretrained=cfg.pretrained,\n            in_chans=cfg.in_channels,\n            drop_rate=0.2,\n            drop_path_rate=0.2\n        )\n        \n        if 'efficientnet' in cfg.model_name:\n            backbone_out = self.backbone.classifier.in_features\n            self.backbone.classifier = nn.Identity()\n        elif 'resnet' in cfg.model_name:\n            backbone_out = self.backbone.fc.in_features\n            self.backbone.fc = nn.Identity()\n        else:\n            backbone_out = self.backbone.get_classifier().in_features\n            self.backbone.reset_classifier(0, '')\n        \n        self.pooling = nn.AdaptiveAvgPool2d(1)\n            \n        self.feat_dim = backbone_out\n        \n        self.classifier = nn.Linear(backbone_out, cfg.num_classes)\n        \n        self.mixup_enabled = hasattr(cfg, 'mixup_alpha') and cfg.mixup_alpha > 0\n        if self.mixup_enabled:\n            self.mixup_alpha = cfg.mixup_alpha\n            \n    def forward(self, x, targets=None):\n    \n        if self.training and self.mixup_enabled and targets is not None:\n            mixed_x, targets_a, targets_b, lam = self.mixup_data(x, targets)\n            x = mixed_x\n        else:\n            targets_a, targets_b, lam = None, None, None\n        \n        features = self.backbone(x)\n        \n        if isinstance(features, dict):\n            features = features['features']\n            \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        \n        if self.training and self.mixup_enabled and targets is not None:\n            loss = self.mixup_criterion(F.binary_cross_entropy_with_logits, \n                                       logits, targets_a, targets_b, lam)\n            return logits, loss\n            \n        return logits\n    \n    def mixup_data(self, x, targets):\n        \"\"\"Applies mixup to the data batch\"\"\"\n        batch_size = x.size(0)\n\n        lam = np.random.beta(self.mixup_alpha, self.mixup_alpha)\n\n        indices = torch.randperm(batch_size).to(x.device)\n\n        mixed_x = lam * x + (1 - lam) * x[indices]\n        \n        return mixed_x, targets, targets[indices], lam\n    \n    def mixup_criterion(self, criterion, pred, y_a, y_b, lam):\n        \"\"\"Applies mixup to the loss function\"\"\"\n        return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:18.325915Z","iopub.execute_input":"2025-06-05T12:26:18.326228Z","iopub.status.idle":"2025-06-05T12:26:18.335615Z","shell.execute_reply.started":"2025-06-05T12:26:18.326202Z","shell.execute_reply":"2025-06-05T12:26:18.334718Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training Utilities\nWe are configuring our optimization strategy with the AdamW optimizer, cosine scheduling, and the BCEWithLogitsLoss criterion.","metadata":{}},{"cell_type":"code","source":"def get_optimizer(model, cfg):\n  \n    if cfg.optimizer == 'Adam':\n        optimizer = optim.Adam(\n            model.parameters(),\n            lr=cfg.lr,\n            weight_decay=cfg.weight_decay\n        )\n    elif cfg.optimizer == 'AdamW':\n        optimizer = optim.AdamW(\n            model.parameters(),\n            lr=cfg.lr,\n            weight_decay=cfg.weight_decay\n        )\n    elif cfg.optimizer == 'SGD':\n        optimizer = optim.SGD(\n            model.parameters(),\n            lr=cfg.lr,\n            momentum=0.9,\n            weight_decay=cfg.weight_decay\n        )\n    else:\n        raise NotImplementedError(f\"Optimizer {cfg.optimizer} not implemented\")\n        \n    return optimizer\n    \n#----------------------------------------------------------\ndef get_scheduler(optimizer, cfg):\n    if cfg.scheduler == 'OneCycleLR':\n        scheduler = lr_scheduler.OneCycleLR(\n            optimizer,\n            max_lr=cfg.lr,  # 最大学习率\n            steps_per_epoch=len(train_loader),  # 每个 epoch 的迭代次数\n            epochs=cfg.epochs,  # 总训练轮数\n            pct_start=cfg.pct_start,  # 学习率增长阶段的比例\n            div_factor=cfg.div_factor,  # 最大学习率与初始学习率的比值\n            final_div_factor=cfg.final_div_factor  # 最大学习率与最终学习率的比值\n        )\n    else:\n        scheduler = None\n    return scheduler\n\ndef get_criterion(cfg):\n \n    if cfg.criterion == 'BCEWithLogitsLoss':\n        criterion = nn.BCEWithLogitsLoss()\n    else:\n        raise NotImplementedError(f\"Criterion {cfg.criterion} not implemented\")\n        \n    return criterion","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:21.377325Z","iopub.execute_input":"2025-06-05T12:26:21.377657Z","iopub.status.idle":"2025-06-05T12:26:21.383784Z","shell.execute_reply.started":"2025-06-05T12:26:21.377628Z","shell.execute_reply":"2025-06-05T12:26:21.382925Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training Loop","metadata":{}},{"cell_type":"code","source":"#---------------------------------------------------------\ndef train_one_epoch(model, loader, optimizer, criterion, device, scheduler=None):\n    model.train()\n    losses = []\n    all_targets = []\n    all_outputs = []\n\n    pbar = tqdm(enumerate(loader), total=len(loader), desc=\"Training\")\n\n    for step, batch in pbar:\n        inputs = batch['melspec'].to(device)\n        targets = batch['target'].to(device)\n\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, targets)\n        loss.backward()\n        optimizer.step()\n\n        # 调整学习率\n        if scheduler is not None:\n            scheduler.step()\n\n        outputs = outputs.detach().cpu().numpy()\n        targets = targets.detach().cpu().numpy()\n\n        all_outputs.append(outputs)\n        all_targets.append(targets)\n        losses.append(loss.item())\n\n        pbar.set_postfix({\n            'train_loss': np.mean(losses[-10:]) if losses else 0,\n            'lr': optimizer.param_groups[0]['lr']\n        })\n\n    all_outputs = np.concatenate(all_outputs)\n    all_targets = np.concatenate(all_targets)\n    auc = calculate_auc(all_targets, all_outputs)\n    avg_loss = np.mean(losses)\n\n    return avg_loss, auc\n\ndef validate(model, loader, criterion, device):\n   \n    model.eval()\n    losses = []\n    all_targets = []\n    all_outputs = []\n    \n    with torch.no_grad():\n        for batch in tqdm(loader, desc=\"Validation\"):\n            if isinstance(batch['melspec'], list):\n                batch_outputs = []\n                batch_losses = []\n                \n                for i in range(len(batch['melspec'])):\n                    inputs = batch['melspec'][i].unsqueeze(0).to(device)\n                    target = batch['target'][i].unsqueeze(0).to(device)\n                    \n                    output = model(inputs)\n                    loss = criterion(output, target)\n                    \n                    batch_outputs.append(output.detach().cpu())\n                    batch_losses.append(loss.item())\n                \n                outputs = torch.cat(batch_outputs, dim=0).numpy()\n                loss = np.mean(batch_losses)\n                targets = batch['target'].numpy()\n                \n            else:\n                inputs = batch['melspec'].to(device)\n                targets = batch['target'].to(device)\n                \n                outputs = model(inputs)\n                loss = criterion(outputs, targets)\n                \n                outputs = outputs.detach().cpu().numpy()\n                targets = targets.detach().cpu().numpy()\n            \n            all_outputs.append(outputs)\n            all_targets.append(targets)\n            losses.append(loss if isinstance(loss, float) else loss.item())\n    \n    all_outputs = np.concatenate(all_outputs)\n    all_targets = np.concatenate(all_targets)\n    \n    auc = calculate_auc(all_targets, all_outputs)\n    avg_loss = np.mean(losses)\n    \n    return avg_loss, auc\n\ndef calculate_auc(targets, outputs):\n  \n    num_classes = targets.shape[1]\n    aucs = []\n    \n    probs = 1 / (1 + np.exp(-outputs))\n    \n    for i in range(num_classes):\n        \n        if np.sum(targets[:, i]) > 0:\n            class_auc = roc_auc_score(targets[:, i], probs[:, i])\n            aucs.append(class_auc)\n    \n    return np.mean(aucs) if aucs else 0.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:24.377985Z","iopub.execute_input":"2025-06-05T12:26:24.378288Z","iopub.status.idle":"2025-06-05T12:26:24.389864Z","shell.execute_reply.started":"2025-06-05T12:26:24.378265Z","shell.execute_reply":"2025-06-05T12:26:24.389093Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training!","metadata":{}},{"cell_type":"code","source":"def run_training(df, cfg):\n    \"\"\"Training function that can either use pre-computed spectrograms or generate them on-the-fly\"\"\"\n\n    taxonomy_df = pd.read_csv(cfg.taxonomy_csv)\n    species_ids = taxonomy_df['primary_label'].tolist()\n    cfg.num_classes = len(species_ids)\n    \n    if cfg.debug:\n        cfg.update_debug_settings()\n\n    spectrograms = {}\n    successful_loads = 0  # Initialize the counter for successful loads\n\n    for npy_file in cfg.spectrogram_npy:\n        try:\n            additional_spectrograms = np.load(npy_file, allow_pickle=True).item()\n            print(f\"Loaded {len(additional_spectrograms)} pre-computed mel spectrograms from {npy_file}\")\n            spectrograms.update(additional_spectrograms)\n            successful_loads += 1\n        except Exception as e:\n            print(f\"Error loading pre-computed spectrograms from {npy_file}: {e}\")\n\n    # Check if all datasets were loaded successfully\n    if successful_loads == len(cfg.spectrogram_npy):\n        print(\"Success: All datasets have been loaded successfully.\")\n    else:\n        print(f\"Warning: Only {successful_loads} out of {len(cfg.spectrogram_npy)} datasets were loaded successfully.\")\n\n    if not cfg.LOAD_DATA:\n        print(\"Will generate spectrograms on-the-fly during training.\")\n        if 'filepath' not in df.columns:\n            df['filepath'] = cfg.train_datadir + '/' + df.filename\n        if 'samplename' not in df.columns:\n            df['samplename'] = df.filename.map(lambda x: x.split('/')[0] + '-' + x.split('/')[-1].split('.')[0])\n        \n    skf = StratifiedKFold(n_splits=7, shuffle=True, random_state=cfg.seed)\n    \n    best_scores = []\n\n    # 在配置对象中添加save_dir属性\n    if not hasattr(cfg, 'save_dir'):\n        cfg.save_dir = 'default_save_dir'  # 设置一个默认的保存目录，你可以根据需要修改\n\n    # 创建保存数据的目录\n    save_dir = os.path.join(cfg.save_dir, \"fold_data\")\n    os.makedirs(save_dir, exist_ok=True)\n    \n    for fold, (train_idx, val_idx) in enumerate(skf.split(df, df['primary_label'])):\n        if fold not in cfg.selected_folds:\n            continue\n            \n        print(f'\\n{\"=\"*30} Fold {fold} {\"=\"*30}')\n        \n        train_df = df.iloc[train_idx].reset_index(drop=True)\n        val_df = df.iloc[val_idx].reset_index(drop=True)\n        \n        print(f'Training set: {len(train_df)} samples')\n        print(f'Validation set: {len(val_df)} samples')\n        \n        train_dataset = BirdCLEFDatasetFromNPY(train_df, cfg, spectrograms=spectrograms, mode='train')\n        val_dataset = BirdCLEFDatasetFromNPY(val_df, cfg, spectrograms=spectrograms, mode='valid')\n        \n        train_loader = DataLoader(\n            train_dataset, \n            batch_size=cfg.batch_size, \n            shuffle=True, \n            num_workers=cfg.num_workers,\n            pin_memory=True,\n            collate_fn=collate_fn,\n            drop_last=True\n        )\n        \n        val_loader = DataLoader(\n            val_dataset, \n            batch_size=cfg.batch_size, \n            shuffle=False, \n            num_workers=cfg.num_workers,\n            pin_memory=True,\n            collate_fn=collate_fn\n        )\n        \n        model = BirdCLEFModel(cfg).to(cfg.device)\n        optimizer = get_optimizer(model, cfg)\n        criterion = get_criterion(cfg)\n        \n        if cfg.scheduler == 'OneCycleLR':\n            scheduler = lr_scheduler.OneCycleLR(\n                optimizer,\n                max_lr=cfg.lr,\n                steps_per_epoch=len(train_loader),\n                epochs=cfg.epochs,\n                pct_start=0.1\n            )\n        else:\n            scheduler = get_scheduler(optimizer, cfg)\n        \n        best_auc = 0\n        best_epoch = 0\n\n        train_losses = []\n        train_aucs = []\n        val_losses = []\n        val_aucs = []\n        \n        for epoch in range(cfg.epochs):\n            print(f\"\\nEpoch {epoch+1}/{cfg.epochs}\")\n            \n            train_loss, train_auc = train_one_epoch(\n                model, \n                train_loader, \n                optimizer, \n                criterion, \n                cfg.device,\n                scheduler if isinstance(scheduler, lr_scheduler.OneCycleLR) else None\n            )\n            \n            val_loss, val_auc = validate(model, val_loader, criterion, cfg.device)\n\n            if scheduler is not None and not isinstance(scheduler, lr_scheduler.OneCycleLR):\n                if isinstance(scheduler, lr_scheduler.ReduceLROnPlateau):\n                    scheduler.step(val_loss)\n                else:\n                    scheduler.step()\n\n            print(f\"Train Loss: {train_loss:.4f}, Train AUC: {train_auc:.4f}\")\n            print(f\"Val Loss: {val_loss:.4f}, Val AUC: {val_auc:.4f}\")\n\n            train_losses.append(train_loss)\n            train_aucs.append(train_auc)\n            val_losses.append(val_loss)\n            val_aucs.append(val_auc)\n            \n            if val_auc > best_auc:\n                best_auc = val_auc\n                best_epoch = epoch + 1\n                print(f\"New best AUC: {best_auc:.4f} at epoch {best_epoch}\")\n\n                torch.save({\n                    'model_state_dict': model.state_dict(),\n                    'optimizer_state_dict': optimizer.state_dict(),\n                    'scheduler_state_dict': scheduler.state_dict() if scheduler else None,\n                    'epoch': epoch,\n                    'val_auc': val_auc,\n                    'train_auc': train_auc,\n                    'cfg': cfg\n                }, f\"model_fold{fold}.pth\")\n\n         # 保存每折的训练和验证的损失值、AUC值\n        fold_data = {\n            \"train_losses\": train_losses,\n            \"train_aucs\": train_aucs,\n            \"val_losses\": val_losses,\n            \"val_aucs\": val_aucs,\n            \"best_auc\": best_auc,\n            \"best_epoch\": best_epoch\n        }\n        np.save(os.path.join(save_dir, f\"fold_{fold}_data.npy\"), fold_data)\n        \n        best_scores.append(best_auc)\n        print(f\"\\nBest AUC for fold {fold}: {best_auc:.4f} at epoch {best_epoch}\")\n        \n        # Clear memory\n        del model, optimizer, scheduler, train_loader, val_loader\n        torch.cuda.empty_cache()\n        gc.collect()\n    \n    print(\"\\n\" + \"=\"*60)\n    print(\"Cross-Validation Results:\")\n    for fold, score in enumerate(best_scores):\n        print(f\"Fold {cfg.selected_folds[fold]}: {score:.4f}\")\n    print(f\"Mean AUC: {np.mean(best_scores):.4f}\")\n    print(\"=\"*60)\n    return best_scores","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:28.415043Z","iopub.execute_input":"2025-06-05T12:26:28.415370Z","iopub.status.idle":"2025-06-05T12:26:28.430608Z","shell.execute_reply.started":"2025-06-05T12:26:28.415345Z","shell.execute_reply":"2025-06-05T12:26:28.429719Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if __name__ == \"__main__\":\n    import time\n    \n    print(\"\\nLoading training data...\")\n    train_df = pd.read_csv(cfg.train_csv)\n    taxonomy_df = pd.read_csv(cfg.taxonomy_csv)\n\n    print(\"\\nStarting training...\")\n    print(f\"LOAD_DATA is set to {cfg.LOAD_DATA}\")\n    if cfg.LOAD_DATA:\n        print(\"Using pre-computed mel spectrograms from NPY file\")\n    else:\n        print(\"Will generate spectrograms on-the-fly during training\")\n    \n    run_training(train_df, cfg)\n    \n    print(\"\\nTraining complete!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-05T12:26:45.374263Z","iopub.execute_input":"2025-06-05T12:26:45.374596Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}