{"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":11060723,"sourceType":"datasetVersion","datasetId":6891568}],"dockerImageVersionId":30918,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Credit goes to this notebook and Author\nhttps://www.kaggle.com/code/kadircandrisolu/efficientnet-b0-pytorch-inference-birdclef-25\n\n## What changed here\nN_MELS !! increased 16\n\n## What's Next - automated code generation and ML model improvement suggestion --> Ongoing & upcoming Kaggle AI models here --> https://www.kaggle.com/organizations/andrometocs/models\n\n## Already exisitng examples here --> Google Gemini Flash API provide better optimized ML code https://www.kaggle.com/code/kumarandatascientist/llm-te-xgb-randomizedsearchcv-baseline-v1\n\n## Deepseek recently created example here --> Model https://www.kaggle.com/models/andrometocs/deepseekcodingpatternpipeline --> code example : https://www.kaggle.com/code/kumarandatascientist/deepseek-coding-with-optimization-and-big-o-alg-v1\n\n1. LLM - Deepseek\n2. LLM latest - Google Gemma 3\n\nAnything helps discuss and comment your suggestions !! Happy Kaggling","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\n\nwarnings.filterwarnings(\"ignore\")\nlogging.basicConfig(level=logging.ERROR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:34.872264Z","iopub.execute_input":"2025-03-17T11:15:34.872768Z","iopub.status.idle":"2025-03-17T11:15:34.879592Z","shell.execute_reply.started":"2025-03-17T11:15:34.872736Z","shell.execute_reply":"2025-03-17T11:15:34.8781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CFG:\n \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    model_path = '/kaggle/input/birdclef25-effnetb0-starter-weight'  \n    \n    # Audio parameters\n    FS = 32000  # Sample rate\n    WINDOW_SIZE = 5  # Size of each prediction window in seconds\n    \n    # Mel spectrogram parameters\n    N_FFT = 960\n    HOP_LENGTH = 512\n    N_MELS = 144\n    FMIN = 50\n    FMAX = 14000\n    TARGET_SHAPE = (256, 256)\n    \n    # Model parameters\n    model_name = 'efficientnet_b0'\n    in_channels = 1\n    device = 'cpu'  # Force CPU as per competition requirements\n    \n    # Inference parameters\n    batch_size = 16\n    use_tta = False  # Whether to use test-time augmentation\n    tta_count = 3   # Number of TTA variations if use_tta is True\n    threshold = 0.5\n    \n    # Ensemble - automatically find model files instead of specifying folds\n    use_specific_folds = False  # If False, use all found models\n    folds = [0, 1]  # Used only if use_specific_folds is True\n    \n    # Flag for debugging with a subset of soundscapes\n    debug = False\n    debug_count = 3\n\ncfg = CFG()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:39.692397Z","iopub.execute_input":"2025-03-17T11:15:39.692762Z","iopub.status.idle":"2025-03-17T11:15:39.699604Z","shell.execute_reply.started":"2025-03-17T11:15:39.692736Z","shell.execute_reply":"2025-03-17T11:15:39.698082Z"}},"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-03-17T11:15:39.894603Z","iopub.execute_input":"2025-03-17T11:15:39.894939Z","iopub.status.idle":"2025-03-17T11:15:39.906783Z","shell.execute_reply.started":"2025-03-17T11:15:39.894914Z","shell.execute_reply":"2025-03-17T11:15:39.905369Z"}},"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,  # No need for pretrained weights during inference\n            in_chans=cfg.in_channels,\n            drop_rate=0.0,     # Disable dropout for inference\n            drop_path_rate=0.0\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        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        \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        return logits\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:40.130048Z","iopub.execute_input":"2025-03-17T11:15:40.130459Z","iopub.status.idle":"2025-03-17T11:15:40.139144Z","shell.execute_reply.started":"2025-03-17T11:15:40.130423Z","shell.execute_reply":"2025-03-17T11:15:40.137936Z"}},"outputs":[],"execution_count":null},{"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_segment(audio_data, cfg):\n    \"\"\"Process audio segment to get mel spectrogram\"\"\"\n    if len(audio_data) < cfg.FS * cfg.WINDOW_SIZE:\n        # Pad if segment is shorter than 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    # Resize if needed\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-03-17T11:15:40.367187Z","iopub.execute_input":"2025-03-17T11:15:40.36761Z","iopub.status.idle":"2025-03-17T11:15:40.375653Z","shell.execute_reply.started":"2025-03-17T11:15:40.367582Z","shell.execute_reply":"2025-03-17T11:15:40.374508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def find_model_files(cfg):\n    \"\"\"\n    Find all .pth model files in the specified model directory\n    \"\"\"\n    model_files = []\n    \n    # Convert the model directory to a Path object\n    model_dir = Path(cfg.model_path)\n    \n    # Find all .pth files, checking all subdirectories\n    for path in model_dir.glob('**/*.pth'):\n        model_files.append(str(path))\n    \n    return model_files\n\ndef load_models(cfg, num_classes):\n    \"\"\"\n    Load all found model files and prepare them for ensemble\n    \"\"\"\n    models = []\n    \n    # Find model files\n    model_files = find_model_files(cfg)\n    \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 specific folds are requested, use only those folds\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    # Load each model file\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            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\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        # Calculate total number of complete 5-second segments\n        total_segments = int(len(audio_data) / (cfg.FS * cfg.WINDOW_SIZE))\n        \n        for segment_idx in range(total_segments):\n            # Extract current 5-second segment\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            # Calculate end time in seconds for row_id\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            # Process the audio segment and get mel spectrogram\n            if cfg.use_tta:\n                # Use test-time augmentation\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                    # Convert to tensor and add batch and channel dimensions\n                    mel_spec = torch.tensor(mel_spec, dtype=torch.float32).unsqueeze(0).unsqueeze(0)\n                    mel_spec = mel_spec.to(cfg.device)\n                    \n                    # Handle single model case without ensemble\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                        # Get predictions from each model for ensemble\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                        \n                        # Average predictions from all models\n                        avg_preds = np.mean(segment_preds, axis=0)\n                        all_preds.append(avg_preds)\n                \n                # Average TTA predictions\n                final_preds = np.mean(all_preds, axis=0)\n            else:\n                # No TTA - just use the original spectrogram\n                mel_spec = process_audio_segment(segment_audio, cfg)\n                \n                # Convert to tensor and add batch and channel dimensions\n                mel_spec = torch.tensor(mel_spec, dtype=torch.float32).unsqueeze(0).unsqueeze(0)\n                mel_spec = mel_spec.to(cfg.device)\n                \n                # Handle single model case without ensemble\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                    # Get predictions from each model for ensemble\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                    \n                    # Average predictions from all models\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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:40.682231Z","iopub.execute_input":"2025-03-17T11:15:40.68261Z","iopub.status.idle":"2025-03-17T11:15:40.699399Z","shell.execute_reply.started":"2025-03-17T11:15:40.682583Z","shell.execute_reply":"2025-03-17T11:15:40.697825Z"}},"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    # Get list of 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    # Initialize lists for predictions\n    all_row_ids = []\n    all_predictions = []\n    \n    # Process each soundscape\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    # Create dictionary with row_ids\n    submission_dict = {'row_id': row_ids}\n    \n    # Add predictions for each species\n    for i, species in enumerate(species_ids):\n        submission_dict[species] = [pred[i] for pred in predictions]\n    \n    # Create dataframe\n    submission_df = pd.DataFrame(submission_dict)\n    \n    # Set row_id as index\n    submission_df.set_index('row_id', inplace=True)\n    \n    # Verify the submission format against sample submission\n    sample_sub = pd.read_csv(cfg.submission_csv, index_col='row_id')\n    \n    # Check if all species columns are present\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        # Add missing columns with zeros\n        for col in missing_cols:\n            submission_df[col] = 0.0\n    \n    # Ensure columns are in the same order as sample submission\n    submission_df = submission_df[sample_sub.columns]\n    \n    # Reset the index to include row_id as a column\n    submission_df = submission_df.reset_index()\n    \n    return submission_df\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:41.267905Z","iopub.execute_input":"2025-03-17T11:15:41.268233Z","iopub.status.idle":"2025-03-17T11:15:41.278321Z","shell.execute_reply.started":"2025-03-17T11:15:41.268209Z","shell.execute_reply":"2025-03-17T11:15:41.276526Z"}},"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    # Load models for ensemble\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    # Run inference on test soundscapes\n    row_ids, predictions = run_inference(cfg, models, species_ids)\n    \n    # Create submission dataframe\n    submission_df = create_submission(row_ids, predictions, species_ids, cfg)\n    \n    # Save submission file\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-03-17T11:15:41.859665Z","iopub.execute_input":"2025-03-17T11:15:41.860048Z","iopub.status.idle":"2025-03-17T11:15:41.867831Z","shell.execute_reply.started":"2025-03-17T11:15:41.860019Z","shell.execute_reply":"2025-03-17T11:15:41.866109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if __name__ == \"__main__\":\n    main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-17T11:15:43.286169Z","iopub.execute_input":"2025-03-17T11:15:43.28654Z","iopub.status.idle":"2025-03-17T11:15:43.570603Z","shell.execute_reply.started":"2025-03-17T11:15:43.286512Z","shell.execute_reply":"2025-03-17T11:15:43.569241Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}