{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":70203,"databundleVersionId":8068726,"sourceType":"competition"},{"sourceId":182353090,"sourceType":"kernelVersion"},{"sourceId":6127,"sourceType":"modelInstanceVersion","modelInstanceId":4598}],"dockerImageVersionId":30733,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"_uuid":"c0cd1c52-6492-49b8-b47a-9a794fdbeb86","_cell_guid":"44b1a976-b596-4535-bbb6-b4dc1a59be45","collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"  # \"jax\" or \"tensorflow\" or \"torch\" \n\nimport keras_cv\nimport keras\nimport keras.backend as K\nimport tensorflow as tf\nimport tensorflow_io as tfio\n\nimport numpy as np \nimport pandas as pd\n\nfrom glob import glob\nfrom tqdm import tqdm\n\nimport librosa\nimport IPython.display as ipd\nimport librosa.display as lid\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\ncmap = mpl.cm.get_cmap('coolwarm')","metadata":{"_uuid":"283d5f74-0de0-4511-8b9f-4f87bdb19f1f","_cell_guid":"d10186f3-3b25-4f3e-94d9-326917491c69","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:21.620693Z","iopub.execute_input":"2024-06-06T09:26:21.621891Z","iopub.status.idle":"2024-06-06T09:26:43.719770Z","shell.execute_reply.started":"2024-06-06T09:26:21.621852Z","shell.execute_reply":"2024-06-06T09:26:43.718664Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG:\n    seed = 42\n    \n    # Input image size and batch size\n    img_size = [128, 384]\n    \n    # Audio duration, sample rate, and length\n    duration = 15 # second\n    sample_rate = 32000\n    audio_len = duration*sample_rate\n    \n    # STFT parameters\n    nfft = 2028\n    window = 2048\n    hop_length = audio_len // (img_size[1] - 1)\n    fmin = 20\n    fmax = 16000\n    \n    # Number of epochs, model name\n    preset = 'efficientnetv2_b2_imagenet'\n\n    # Class Labels for BirdCLEF 24\n    class_names = sorted(os.listdir('/kaggle/input/birdclef-2024/train_audio'))\n    num_classes = len(class_names)\n    class_labels = list(range(num_classes))\n    label2name = dict(zip(class_labels, class_names))\n    name2label = {v:k for k,v in label2name.items()}","metadata":{"_uuid":"fc1a74a5-3979-4a1a-a719-657f2ce0476e","_cell_guid":"0ad3cf01-3e21-46e4-a55c-1fec315cb0ec","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:43.721729Z","iopub.execute_input":"2024-06-06T09:26:43.722515Z","iopub.status.idle":"2024-06-06T09:26:43.743080Z","shell.execute_reply.started":"2024-06-06T09:26:43.722479Z","shell.execute_reply":"2024-06-06T09:26:43.741943Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.set_random_seed(CFG.seed)","metadata":{"_uuid":"975cf5ab-6659-4660-ac58-f6d5cf70b93d","_cell_guid":"f0798218-4ed7-4761-a606-ee67027bf29d","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:43.744466Z","iopub.execute_input":"2024-06-06T09:26:43.744908Z","iopub.status.idle":"2024-06-06T09:26:43.762079Z","shell.execute_reply.started":"2024-06-06T09:26:43.744867Z","shell.execute_reply":"2024-06-06T09:26:43.760919Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = '/kaggle/input/birdclef-2024'","metadata":{"_uuid":"d1397cf1-84e6-4e2d-bfb5-db85ed89a48a","_cell_guid":"fc24bb65-4d03-417c-9ec8-245ea7a2f63a","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:43.764697Z","iopub.execute_input":"2024-06-06T09:26:43.765150Z","iopub.status.idle":"2024-06-06T09:26:43.770602Z","shell.execute_reply.started":"2024-06-06T09:26:43.765121Z","shell.execute_reply":"2024-06-06T09:26:43.769703Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_paths = glob(f'{BASE_PATH}/test_soundscapes/*ogg')\n# During commit use `unlabeled` data as there is no `test` data.\n# During submission `test` data will automatically be populated.\nif len(test_paths)==0:\n    test_paths = glob(f'{BASE_PATH}/unlabeled_soundscapes/*ogg')[:10]\ntest_df = pd.DataFrame(test_paths, columns=['filepath'])\ntest_df.head()","metadata":{"_uuid":"f8914d2c-c25d-4032-a6ab-970739344740","_cell_guid":"565171a6-d9fc-4371-841f-10d39b7cdaec","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:43.772113Z","iopub.execute_input":"2024-06-06T09:26:43.772665Z","iopub.status.idle":"2024-06-06T09:26:43.922945Z","shell.execute_reply.started":"2024-06-06T09:26:43.772632Z","shell.execute_reply":"2024-06-06T09:26:43.921820Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create an input layer for the model\ninp = keras.layers.Input(shape=(None, None, 3))\n# Pretrained backbone\nbackbone = keras_cv.models.EfficientNetV2Backbone.from_preset(\n    CFG.preset,\n)\nout = keras_cv.models.ImageClassifier(\n    backbone=backbone,\n    num_classes=CFG.num_classes,\n    name=\"classifier\"\n)(inp)\n# Build model\nmodel = keras.models.Model(inputs=inp, outputs=out)\n# Load weights of trained model\n\n\nmodel.load_weights('/kaggle/input/bird-song/best_model.weights.h5')","metadata":{"_uuid":"d25220f6-b192-4fdd-a650-ad68bd015749","_cell_guid":"d565facf-3e50-4be3-b220-baf2cb03259c","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:43.924376Z","iopub.execute_input":"2024-06-06T09:26:43.924781Z","iopub.status.idle":"2024-06-06T09:26:54.202303Z","shell.execute_reply.started":"2024-06-06T09:26:43.924737Z","shell.execute_reply":"2024-06-06T09:26:54.201260Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Decodes Audio\ndef build_decoder(with_labels=True, dim=1024):\n    def get_audio(filepath):\n        file_bytes = tf.io.read_file(filepath)\n        audio = tfio.audio.decode_vorbis(file_bytes) # decode .ogg file\n        audio = tf.cast(audio, tf.float32)\n        if tf.shape(audio)[1]>1: # stereo -> mono\n            audio = audio[...,0:1]\n        audio = tf.squeeze(audio, axis=-1)\n        return audio\n    \n    def create_frames(audio, duration=5, sr=32000):\n        frame_size = int(duration * sr)\n        audio = tf.pad(audio[..., None], [[0, tf.shape(audio)[0] % frame_size], [0, 0]]) # pad the end\n        audio = tf.squeeze(audio) # remove extra dimension added for padding\n        frames = tf.reshape(audio, [-1, frame_size]) # shape: [num_frames, frame_size]\n        return frames\n    \n    def apply_preproc(spec):\n        # Standardize\n        mean = tf.math.reduce_mean(spec)\n        std = tf.math.reduce_std(spec)\n        spec = tf.where(tf.math.equal(std, 0), spec - mean, (spec - mean) / std)\n\n        # Normalize using Min-Max\n        min_val = tf.math.reduce_min(spec)\n        max_val = tf.math.reduce_max(spec)\n        spec = tf.where(tf.math.equal(max_val - min_val, 0), spec - min_val,\n                              (spec - min_val) / (max_val - min_val))\n        return spec\n\n    def decode(path):\n        # Load audio file\n        audio = get_audio(path)\n        # Split audio file into frames with each having 5 seecond duration\n        audio = create_frames(audio)\n        # Convert audio to spectrogram\n        spec = keras.layers.MelSpectrogram(num_mel_bins=CFG.img_size[0],\n                                             fft_length=CFG.nfft, \n                                              sequence_stride=CFG.hop_length, \n                                              sampling_rate=CFG.sample_rate)(audio)\n        # Apply normalization and standardization\n        spec = apply_preproc(spec)\n        # Covnert spectrogram to 3 channel image (for imagenet)\n        spec = tf.tile(spec[..., None], [1, 1, 1, 3])\n        return spec\n    \n    return decode","metadata":{"_uuid":"fed8fc42-ece4-489b-8a02-7e049237e251","_cell_guid":"30f080e4-c60f-4078-b4b0-cd2cef498654","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:54.204095Z","iopub.execute_input":"2024-06-06T09:26:54.204458Z","iopub.status.idle":"2024-06-06T09:26:54.219945Z","shell.execute_reply.started":"2024-06-06T09:26:54.204428Z","shell.execute_reply":"2024-06-06T09:26:54.218814Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Build data loader\ndef build_dataset(paths, batch_size=1, decode_fn=None, cache=False):\n    if decode_fn is None:\n        decode_fn = build_decoder(dim=CFG.audio_len) # decoder\n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = (paths,)\n    ds = tf.data.Dataset.from_tensor_slices(slices)\n    ds = ds.map(decode_fn, num_parallel_calls=AUTO) # decode audio to spectrograms then create frames\n    ds = ds.cache() if cache else ds # cache files\n    ds = ds.batch(batch_size, drop_remainder=False) # create batches\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"_uuid":"f816ca6a-7951-4a90-a05b-d6d6b3970b26","_cell_guid":"288751d3-1740-407d-8744-05d1025883bf","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:54.221585Z","iopub.execute_input":"2024-06-06T09:26:54.221984Z","iopub.status.idle":"2024-06-06T09:26:54.234230Z","shell.execute_reply.started":"2024-06-06T09:26:54.221953Z","shell.execute_reply":"2024-06-06T09:26:54.233326Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialize empty list to store ids\nids = []\n\n# Initialize empty array to store predictions\npreds = np.empty(shape=(0, CFG.num_classes), dtype='float32')\n\n# Build test dataset\ntest_paths = test_df.filepath.tolist()\ntest_ds = build_dataset(paths=test_paths, batch_size=1)\n\n# Iterate over each audio file in the test dataset\nfor idx, specs in enumerate(tqdm(iter(test_ds), desc='test ', total=len(test_df))):\n    # Extract the filename without the extension\n    filename = test_paths[idx].split('/')[-1].replace('.ogg','')\n    \n    # Convert to backend-specific tensor while excluding extra dimension\n    specs = keras.ops.convert_to_tensor(specs[0])\n    \n    # Predict bird species for all frames in a recording using all trained models\n    frame_preds = model.predict(specs, verbose=0)\n    \n    # Create a ID for each frame in a recording using the filename and frame number\n    frame_ids = [f'{filename}_{(frame_id+1)*5}' for frame_id in range(len(frame_preds))]\n    \n    # Concatenate the ids\n    ids += frame_ids\n    # Concatenate the predictions\n    preds = np.concatenate([preds, frame_preds], axis=0)","metadata":{"_uuid":"d85977a7-0e15-49e4-9734-674cf61ec889","_cell_guid":"d3029dab-f525-4a9e-91ca-444517ae0afe","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:26:54.235852Z","iopub.execute_input":"2024-06-06T09:26:54.236199Z","iopub.status.idle":"2024-06-06T09:27:16.394604Z","shell.execute_reply.started":"2024-06-06T09:26:54.236170Z","shell.execute_reply":"2024-06-06T09:27:16.393381Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submit prediction\npred_df = pd.DataFrame(ids, columns=['row_id'])\npred_df.loc[:, CFG.class_names] = preds\npred_df.to_csv('submission.csv',index=False)\npred_df.head()","metadata":{"_uuid":"d7dbbb9c-d71d-4f58-9869-b3584d9a4f80","_cell_guid":"67f59d25-66b3-423b-b44f-209f520ff65a","collapsed":false,"execution":{"iopub.status.busy":"2024-06-06T09:27:16.398035Z","iopub.execute_input":"2024-06-06T09:27:16.398425Z","iopub.status.idle":"2024-06-06T09:27:16.706566Z","shell.execute_reply.started":"2024-06-06T09:27:16.398380Z","shell.execute_reply":"2024-06-06T09:27:16.705157Z"},"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]}]}