{"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":"none","dataSources":[{"sourceId":91844,"databundleVersionId":11361821,"sourceType":"competition"},{"sourceId":11053663,"sourceType":"datasetVersion","datasetId":6886569},{"sourceId":11918002,"sourceType":"datasetVersion","datasetId":7492364}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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.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\nimport torchaudio\nfrom torchvision.ops import sigmoid_focal_loss\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)\n\nclass FocalLoss(nn.Module):\n    def __init__(self, alpha=0.25, gamma=2.0, reduction='mean'):\n        super().__init__()\n        self.alpha = alpha\n        self.gamma = gamma\n        self.reduction = reduction\n\n    def forward(self, inputs, targets):\n        return sigmoid_focal_loss(\n            inputs, targets,\n            alpha=self.alpha,\n            gamma=self.gamma,\n            reduction=self.reduction\n        )\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:16:48.199305Z","iopub.execute_input":"2025-05-23T11:16:48.199745Z","iopub.status.idle":"2025-05-23T11:17:06.144396Z","shell.execute_reply.started":"2025-05-23T11:16:48.199702Z","shell.execute_reply":"2025-05-23T11:17:06.143410Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Configuration","metadata":{}},{"cell_type":"code","source":"class CFG:\n    \n    seed = 42\n    debug = True  \n    apex = False\n    print_freq = 100\n    num_workers = 2  # 제출 환경에선 2 초과 X\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'\n \n    model_name = 'efficientnet_b0'  \n    pretrained = True\n    in_channels = 1\n\n    LOAD_DATA = True  \n    FS = 32000   # 1초\n    TARGET_DURATION = 5.0   # 5초 분할이 최적인가?\n    TARGET_SHAPE = (256, 256)\n    \n    N_FFT = 1024 # 512, 1024, 2048 실험\n    HOP_LENGTH = 512 # N_FFT의 절반 혹은 반의반\n    N_MELS = 128 # 64, 128, 256 실험. 커질수록 연산량 증가\n    FMIN = 50 # 불필요한 저주파 소리 제거. 50보단 높이는 게 좋은가? soundscape 주파수 대역을 확인해보자.\n    FMAX = 14000 # 불필요한 고주파 소리 제거. 14000보단 낯추어도 될듯? 새소리들의 주파수 대역을 확인해보자.\n    \n    device = 'cuda' if torch.cuda.is_available() else 'cpu'\n    epochs = 10  # 경량화 이후 20까지 올리기.\n    batch_size = 32  # 32가 최대인듯?\n    criterion = 'FocalBCE' #'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    scheduler = 'CosineAnnealingLR'\n    min_lr = 1e-6\n    T_max = epochs\n\n    aug_prob = 0.5  # 일단은 변경 X\n    mixup_alpha = 0.4  # 일단은 변경 X\n\n    def update_debug_settings(self):\n        if self.debug:\n            self.epochs = 2\n            self.selected_folds = [0]\n\ncfg = CFG()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.145451Z","iopub.execute_input":"2025-05-23T11:17:06.145796Z","iopub.status.idle":"2025-05-23T11:17:06.159174Z","shell.execute_reply.started":"2025-05-23T11:17:06.145766Z","shell.execute_reply":"2025-05-23T11:17:06.157615Z"}},"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-05-23T11:17:06.160799Z","iopub.execute_input":"2025-05-23T11:17:06.161255Z","iopub.status.idle":"2025-05-23T11:17:06.199906Z","shell.execute_reply.started":"2025-05-23T11:17:06.161204Z","shell.execute_reply":"2025-05-23T11:17:06.198494Z"}},"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        if start is not None and stop is not None:\n            start_sample = int(start * cfg.FS)\n            stop_sample = int(stop * cfg.FS)\n            audio_data = audio_data[start_sample:stop_sample]\n        \n        target_samples = int(cfg.TARGET_DURATION * cfg.FS)\n\n        if len(audio_data) < target_samples:\n            n_copy = math.ceil(target_samples / len(audio_data))\n            if n_copy > 1:\n                audio_data = np.concatenate([audio_data] * n_copy)\n\n        # === random 5 sec ===\n        max_start = len(audio_data) - target_samples\n        if max_start > 0:\n            rand_start_idx = random.randint(0, max_start)\n            rand_end_idx = rand_start_idx + target_samples\n            selected_audio = audio_data[rand_start_idx:rand_end_idx]\n        else:\n            selected_audio = audio_data[:target_samples]\n\n        if len(selected_audio) < target_samples:\n            n_repeat = int(np.ceil(target_samples / len(selected_audio)))\n            selected_audio = np.tile(selected_audio, n_repeat)[:target_samples]\n\n        mel_spec = audio2melspec(selected_audio, cfg)\n\n        if mel_spec.shape != cfg.TARGET_SHAPE:\n            mel_spec = np.resize(mel_spec, cfg.TARGET_SHAPE)\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    return all_bird_data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.201049Z","iopub.execute_input":"2025-05-23T11:17:06.201527Z","iopub.status.idle":"2025-05-23T11:17:06.217022Z","shell.execute_reply.started":"2025-05-23T11:17:06.201456Z","shell.execute_reply":"2025-05-23T11:17:06.215773Z"}},"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        self.df = df\n        self.cfg = cfg\n        self.mode = mode\n\n        self.spectrograms = spectrograms\n\n        fabio_csv_path = '/kaggle/input/fabio-csv/fabio.csv'\n        fabio_df = pd.read_csv(fabio_csv_path)\n        self.fabio_intervals = {row['filename']: (row['start'], row['stop']) for _, row in fabio_df.iterrows()}\n        \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        if 'filepath' not in self.df.columns:\n            self.df['filepath'] = self.cfg.train_datadir + '/' + self.df.filename\n        \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        sample_names = set(self.df['samplename'])\n        if self.spectrograms:\n            found_samples = sum(1 for name in sample_names if name in self.spectrograms)\n            print(f\"Found {found_samples} matching spectrograms for {mode} dataset out of {len(self.df)} samples\")\n        \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 len(self.df)\n    \n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        samplename = row['samplename']\n        spec = None\n\n        if self.spectrograms and samplename in self.spectrograms:\n            spec = self.spectrograms[samplename]\n        elif not self.cfg.LOAD_DATA:\n            spec = process_audio_file(row['filepath'], self.cfg)\n            filename = row['filename']\n            if filename in self.fabio_intervals:\n                start, stop = self.fabio_intervals[filename]\n                spec = process_audio_file(row['filepath'], self.cfg, start=start, stop=stop)\n            else:\n                spec = process_audio_file(row['filepath'], self.cfg)\n\n\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        spec = torch.tensor(spec, dtype=torch.float32).unsqueeze(0)  # Add channel dimension\n\n        if self.mode == \"train\" and random.random() < self.cfg.aug_prob:\n            spec = self.apply_spec_augmentations(spec)\n        \n        target = self.encode_label(row['primary_label'])\n        \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        \"\"\"Apply augmentations to 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        # RandAug\n        if random.random() < 0.5:\n            aug_choice = random.choice(['gaussian_noise', 'freq_shift'])\n            if aug_choice == 'gaussian_noise':\n                noise = torch.randn_like(spec) * 0.05\n                spec = spec + noise\n                spec = torch.clamp(spec, 0, 1)\n            elif aug_choice == 'freq_shift':\n                shift = random.randint(-5, 5)\n                # 주파수 축(1번 axis) 기준 이동 (spec shape: [1, F, T])\n                spec = torch.roll(spec, shifts=shift, dims=1)\n    \n        # RandomErasing\n        if random.random() < 0.5:\n            erase_height = random.randint(5, 20)\n            erase_width = random.randint(5, 20)\n            max_x = spec.shape[2] - erase_width\n            max_y = spec.shape[1] - erase_height\n            if max_x > 0 and max_y > 0:\n                x = random.randint(0, max_x)\n                y = random.randint(0, max_y)\n                spec[0, y:y+erase_height, x:x+erase_width] = 0\n            \n        return spec\n    \n    def encode_label(self, label):\n        \"\"\"Encode label to one-hot vector\"\"\"\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-05-23T11:17:06.219718Z","iopub.execute_input":"2025-05-23T11:17:06.220055Z","iopub.status.idle":"2025-05-23T11:17:06.251279Z","shell.execute_reply.started":"2025-05-23T11:17:06.220028Z","shell.execute_reply":"2025-05-23T11:17:06.249622Z"}},"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-05-23T11:17:06.253053Z","iopub.execute_input":"2025-05-23T11:17:06.253389Z","iopub.status.idle":"2025-05-23T11:17:06.279878Z","shell.execute_reply.started":"2025-05-23T11:17:06.253362Z","shell.execute_reply":"2025-05-23T11:17:06.278627Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**각 Mel-spectrogram에서 \"새소리 구간\"만 담긴 구간을 직사각형 칸으로 담은 sub-mel-spectrogram을 추출합니다. 한 Mel-spectrogram에 새소리가 여러 번 담겨 있다면 중복 없이 대표 하나만 선정하여 추출합니다.**","metadata":{}},{"cell_type":"code","source":"# def extract_representative_sub_melspec(\n#     mel_spectrogram,\n#     cfg,\n#     threshold=0.3,\n#     min_duration_frames=5,\n#     max_duration_sec=3.0\n# ):\n#     \"\"\"\n#     Mel-spectrogram에서 새소리 구간만 추출하고, 대표 구간(가장 긴 구간, 단 최대 3초)을 반환합니다.\n\n#     Parameters:\n#         mel_spectrogram (np.ndarray): (n_mels, time_frames) 형태의 Mel-spectrogram\n#         cfg: 설정 객체 (cfg.HOP_LENGTH, cfg.FS 필요)\n#         threshold (float): 에너지 임계값 (0~1)\n#         min_duration_frames (int): 최소 연속 프레임 수\n#         max_duration_sec (float): 최대 구간 길이(초)\n\n#     Returns:\n#         sub_mel_spectrogram (np.ndarray): 추출된 대표 sub-mel-spectrogram\n#         (start_frame, end_frame) (tuple): 대표 구간의 시작/끝 프레임 인덱스\n#     \"\"\"\n#     # 프레임당 시간(초)\n#     frame_time = cfg.HOP_LENGTH / cfg.FS\n#     max_duration_frames = int(max_duration_sec / frame_time)\n\n#     # 시간축으로 에너지 합산\n#     time_energy = mel_spectrogram.sum(axis=0)\n#     # [0,1] 정규화\n#     time_energy_norm = (time_energy - time_energy.min()) / (time_energy.max() - time_energy.min() + 1e-8)\n#     # threshold 이상인 프레임 탐색\n#     active_frames = time_energy_norm > threshold\n\n#     # 연속된 활성 구간(segment) 탐색\n#     segments = []\n#     start = None\n#     for i, val in enumerate(active_frames):\n#         if val and start is None:\n#             start = i\n#         elif not val and start is not None:\n#             if i - start >= min_duration_frames:\n#                 segments.append((start, i-1))\n#             start = None\n#     # 마지막 구간 처리\n#     if start is not None and len(active_frames) - start >= min_duration_frames:\n#         segments.append((start, len(active_frames)-1))\n\n#     if not segments:\n#         return mel_spectrogram, (0, mel_spectrogram.shape[1]-1)\n\n#     # 가장 긴 구간 선택 (단, 최대 max_duration_frames로 제한)\n#     longest_segment = max(segments, key=lambda x: x[1]-x[0])\n#     seg_start, seg_end = longest_segment\n#     seg_len = seg_end - seg_start + 1\n\n#     if seg_len > max_duration_frames:\n#         # 구간이 너무 길면 앞쪽 max_duration_frames만 사용\n#         seg_end = seg_start + max_duration_frames - 1\n\n#     sub_mel_spectrogram = mel_spectrogram[:, seg_start:seg_end+1]\n#     return sub_mel_spectrogram, (seg_start, seg_end)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.281193Z","iopub.execute_input":"2025-05-23T11:17:06.281605Z","iopub.status.idle":"2025-05-23T11:17:06.305052Z","shell.execute_reply.started":"2025-05-23T11:17:06.281556Z","shell.execute_reply":"2025-05-23T11:17:06.303947Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import os\n# import numpy as np\n# import librosa\n# import math\n# from scipy.ndimage import zoom\n# import matplotlib.pyplot as plt\n# %matplotlib inline\n\n# folder_path = os.path.join(cfg.train_datadir, '134933')\n# file_list = [f for f in os.listdir(folder_path) if f.endswith('.ogg')]\n# print(folder_path)\n\n# for filename in file_list:\n#     file_path = os.path.join(folder_path, filename)\n#     mel_spec = process_audio_file(file_path, cfg)\n#     if mel_spec is None:\n#         print(f\"Failed to process {filename}\")\n#         continue\n#     sub_mel_spec, (start_frame, end_frame) = extract_representative_sub_melspec(mel_spec, c)\n#     print(f\"\\nFile: {filename}\")\n#     print(f\"  Mel-spec shape: {mel_spec.shape}\")\n#     print(f\"  Selected segment: {start_frame} ~ {end_frame}\")\n#     print(f\"  Sub mel-spec shape: {sub_mel_spec.shape}\")\n\n#     # (옵션) 시각화\n#     plt.figure(figsize=(12, 5))\n#     plt.subplot(2, 1, 1)\n#     plt.title(f\"{filename} - Mel-spectrogram (sum over mel bands)\")\n#     plt.plot(mel_spec.sum(axis=0))\n#     plt.axvspan(start_frame, end_frame, color='red', alpha=0.3, label='Selected segment')\n#     plt.legend()\n#     plt.subplot(2, 1, 2)\n#     plt.title(\"Extracted Sub Mel-spectrogram (sum over mel bands)\")\n#     plt.plot(sub_mel_spec.sum(axis=0))\n#     plt.tight_layout()\n#     plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.306210Z","iopub.execute_input":"2025-05-23T11:17:06.306633Z","iopub.status.idle":"2025-05-23T11:17:06.329848Z","shell.execute_reply.started":"2025-05-23T11:17:06.306601Z","shell.execute_reply":"2025-05-23T11:17:06.328735Z"}},"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-05-23T11:17:06.330932Z","iopub.execute_input":"2025-05-23T11:17:06.331371Z","iopub.status.idle":"2025-05-23T11:17:06.352104Z","shell.execute_reply.started":"2025-05-23T11:17:06.331343Z","shell.execute_reply":"2025-05-23T11:17:06.350816Z"}},"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\ndef get_scheduler(optimizer, cfg):\n   \n    if cfg.scheduler == 'CosineAnnealingLR':\n        scheduler = lr_scheduler.CosineAnnealingLR(\n            optimizer,\n            T_max=cfg.T_max,\n            eta_min=cfg.min_lr\n        )\n    elif cfg.scheduler == 'ReduceLROnPlateau':\n        scheduler = lr_scheduler.ReduceLROnPlateau(\n            optimizer,\n            mode='min',\n            factor=0.5,\n            patience=2,\n            min_lr=cfg.min_lr,\n            verbose=True\n        )\n    elif cfg.scheduler == 'StepLR':\n        scheduler = lr_scheduler.StepLR(\n            optimizer,\n            step_size=cfg.epochs // 3,\n            gamma=0.5\n        )\n    elif cfg.scheduler == 'OneCycleLR':\n        scheduler = None  \n    else:\n        scheduler = None\n        \n    return scheduler\n\ndef get_criterion(cfg):\n \n    if cfg.criterion == 'BCEWithLogitsLoss':\n        criterion = nn.BCEWithLogitsLoss()\n    elif cfg.criterion == 'FocalBCE':\n        criterion = FocalLoss(alpha=0.25, gamma=2.0, reduction='mean') # alpha, gamma 튜닝은 나중 일.\n    else:\n        raise NotImplementedError(f\"Criterion {cfg.criterion} not implemented\")\n        \n    return criterion","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.353580Z","iopub.execute_input":"2025-05-23T11:17:06.354015Z","iopub.status.idle":"2025-05-23T11:17:06.383025Z","shell.execute_reply.started":"2025-05-23T11:17:06.353969Z","shell.execute_reply":"2025-05-23T11:17:06.381874Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training Loop","metadata":{}},{"cell_type":"code","source":"def train_one_epoch(model, loader, optimizer, criterion, device, scheduler=None):\n    \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    \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                optimizer.zero_grad()\n                output = model(inputs)\n                loss = criterion(output, target)\n                loss.backward()\n                \n                batch_outputs.append(output.detach().cpu())\n                batch_losses.append(loss.item())\n            \n            optimizer.step()\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            optimizer.zero_grad()\n            outputs = model(inputs)\n            \n            if isinstance(outputs, tuple):\n                outputs, loss = outputs  \n            else:\n                loss = criterion(outputs, targets)\n                \n            loss.backward()\n            optimizer.step()\n            \n            outputs = outputs.detach().cpu().numpy()\n            targets = targets.detach().cpu().numpy()\n        \n        if scheduler is not None and isinstance(scheduler, lr_scheduler.OneCycleLR):\n            scheduler.step()\n            \n        all_outputs.append(outputs)\n        all_targets.append(targets)\n        losses.append(loss if isinstance(loss, float) else 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\n# def 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-05-23T11:17:06.384428Z","iopub.execute_input":"2025-05-23T11:17:06.384815Z","iopub.status.idle":"2025-05-23T11:17:06.410980Z","shell.execute_reply.started":"2025-05-23T11:17:06.384779Z","shell.execute_reply":"2025-05-23T11:17:06.409871Z"}},"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 = None\n    if cfg.LOAD_DATA:\n        print(\"Loading pre-computed mel spectrograms from NPY file...\")\n        try:\n            spectrograms = np.load(cfg.spectrogram_npy, allow_pickle=True).item()\n            print(f\"Loaded {len(spectrograms)} pre-computed mel spectrograms\")\n        except Exception as e:\n            print(f\"Error loading pre-computed spectrograms: {e}\")\n            print(\"Will generate spectrograms on-the-fly instead.\")\n            cfg.LOAD_DATA = False\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    print(f\"\\n{'='*30} Training on all data {'='*30}\")\n    print(f'Training set: {len(df)} samples')\n    \n    train_dataset = BirdCLEFDatasetFromNPY(df, cfg, spectrograms=spectrograms, mode='train')\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    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    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        if scheduler is not None and not isinstance(scheduler, lr_scheduler.OneCycleLR):\n            if isinstance(scheduler, lr_scheduler.ReduceLROnPlateau):\n                scheduler.step(train_loss)\n            else:\n                scheduler.step()\n\n        print(f\"Train Loss: {train_loss:.4f}, Train AUC: {train_auc:.4f}\")\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            'train_auc': train_auc,\n            'cfg': cfg\n        }, f\"model_all_data_epoch{epoch+1}.pth\")\n    \n    print(\"\\n\" + \"=\"*60)\n    print(\"Training completed on all data.\")\n    print(\"=\"*60)\n    \n    # Clear memory\n    del model, optimizer, scheduler, train_loader\n    torch.cuda.empty_cache()\n    gc.collect()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-23T11:17:06.412040Z","iopub.execute_input":"2025-05-23T11:17:06.412357Z","iopub.status.idle":"2025-05-23T11:17:06.433214Z","shell.execute_reply.started":"2025-05-23T11:17:06.412329Z","shell.execute_reply":"2025-05-23T11:17:06.431709Z"}},"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-05-23T11:17:06.434505Z","iopub.execute_input":"2025-05-23T11:17:06.434822Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}