{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":70203,"databundleVersionId":8068726,"sourceType":"competition"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nos.environ[\"KERAS_BACKEND\"] = \"jax\"  # \"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":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-17T04:33:10.962637Z","iopub.execute_input":"2024-06-17T04:33:10.963268Z","iopub.status.idle":"2024-06-17T04:33:30.037223Z","shell.execute_reply.started":"2024-06-17T04:33:10.963242Z","shell.execute_reply":"2024-06-17T04:33:30.036134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"TensorFlow:\", tf.__version__)\nprint(\"Keras:\", keras.__version__)\nprint(\"KerasCV:\", keras_cv.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.039179Z","iopub.execute_input":"2024-06-17T04:33:30.040400Z","iopub.status.idle":"2024-06-17T04:33:30.045418Z","shell.execute_reply.started":"2024-06-17T04:33:30.040362Z","shell.execute_reply":"2024-06-17T04:33:30.044411Z"},"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    batch_size = 64\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    epochs = 10\n    preset = 'efficientnetv2_b2_imagenet'\n    \n    # Data augmentation parameters\n    augment=True\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":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.051967Z","iopub.execute_input":"2024-06-17T04:33:30.052454Z","iopub.status.idle":"2024-06-17T04:33:30.086096Z","shell.execute_reply.started":"2024-06-17T04:33:30.052423Z","shell.execute_reply":"2024-06-17T04:33:30.085383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.set_random_seed(CFG.seed)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.087130Z","iopub.execute_input":"2024-06-17T04:33:30.087449Z","iopub.status.idle":"2024-06-17T04:33:30.091894Z","shell.execute_reply.started":"2024-06-17T04:33:30.087420Z","shell.execute_reply":"2024-06-17T04:33:30.091121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = '/kaggle/input/birdclef-2024'","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.093118Z","iopub.execute_input":"2024-06-17T04:33:30.093459Z","iopub.status.idle":"2024-06-17T04:33:30.099667Z","shell.execute_reply.started":"2024-06-17T04:33:30.093430Z","shell.execute_reply":"2024-06-17T04:33:30.098790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(f'{BASE_PATH}/train_metadata.csv')\ndf['filepath'] = BASE_PATH + '/train_audio/' + df.filename\ndf['target'] = df.primary_label.map(CFG.name2label)\ndf['filename'] = df.filepath.map(lambda x: x.split('/')[-1])\ndf['xc_id'] = df.filepath.map(lambda x: x.split('/')[-1].split('.')[0])\n\n# Display rwos\ndf.head(2)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.100963Z","iopub.execute_input":"2024-06-17T04:33:30.101277Z","iopub.status.idle":"2024-06-17T04:33:30.332174Z","shell.execute_reply.started":"2024-06-17T04:33:30.101254Z","shell.execute_reply":"2024-06-17T04:33:30.331028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_audio(filepath):\n    audio, sr = librosa.load(filepath)\n    return audio, sr\n\ndef get_spectrogram(audio):\n    spec = librosa.feature.melspectrogram(y=audio, \n                                   sr=CFG.sample_rate, \n                                   n_mels=256,\n                                   n_fft=2048,\n                                   hop_length=512,\n                                   fmax=CFG.fmax,\n                                   fmin=CFG.fmin,\n                                   )\n    spec = librosa.power_to_db(spec, ref=1.0)\n    min_ = spec.min()\n    max_ = spec.max()\n    if max_ != min_:\n        spec = (spec - min_)/(max_ - min_)\n    return spec\n\ndef display_audio(row):\n    # Caption for viz\n    caption = f'Id: {row.filename} | Name: {row.common_name} | Sci.Name: {row.scientific_name} | Rating: {row.rating}'\n    # Read audio file\n    audio, sr = load_audio(row.filepath)\n    # Keep fixed length audio\n    audio = audio[:CFG.audio_len]\n    # Spectrogram from audio\n    spec = get_spectrogram(audio)\n    # Display audio\n    print(\"# Audio:\")\n    display(ipd.Audio(audio, rate=CFG.sample_rate))\n    print('# Visualization:')\n    fig, ax = plt.subplots(2, 1, figsize=(12, 2*3), sharex=True, tight_layout=True)\n    fig.suptitle(caption)\n    # Waveplot\n    lid.waveshow(audio,\n                 sr=CFG.sample_rate,\n                 ax=ax[0],\n                 color= cmap(0.1))\n    # Specplot\n    lid.specshow(spec, \n                 sr = CFG.sample_rate, \n                 hop_length=512,\n                 n_fft=2048,\n                 fmin=CFG.fmin,\n                 fmax=CFG.fmax,\n                 x_axis = 'time', \n                 y_axis = 'mel',\n                 cmap = 'coolwarm',\n                 ax=ax[1])\n    ax[0].set_xlabel('');\n    fig.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.333610Z","iopub.execute_input":"2024-06-17T04:33:30.333878Z","iopub.status.idle":"2024-06-17T04:33:30.345114Z","shell.execute_reply.started":"2024-06-17T04:33:30.333855Z","shell.execute_reply":"2024-06-17T04:33:30.344161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import required packages\nfrom sklearn.model_selection import train_test_split\n\ntrain_df, valid_df = train_test_split(df, test_size=0.2)\n\nprint(f\"Num Train: {len(train_df)} | Num Valid: {len(valid_df)}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.346213Z","iopub.execute_input":"2024-06-17T04:33:30.346469Z","iopub.status.idle":"2024-06-17T04:33:30.778266Z","shell.execute_reply.started":"2024-06-17T04:33:30.346447Z","shell.execute_reply":"2024-06-17T04:33:30.777287Z"},"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 crop_or_pad(audio, target_len, pad_mode=\"constant\"):\n        audio_len = tf.shape(audio)[0]\n        diff_len = abs(\n            target_len - audio_len\n        )  # find difference between target and audio length\n        if audio_len < target_len:  # do padding if audio length is shorter\n            pad1 = tf.random.uniform([], maxval=diff_len, dtype=tf.int32)\n            pad2 = diff_len - pad1\n            audio = tf.pad(audio, paddings=[[pad1, pad2]], mode=pad_mode)\n        elif audio_len > target_len:  # do cropping if audio length is larger\n            idx = tf.random.uniform([], maxval=diff_len, dtype=tf.int32)\n            audio = audio[idx : (idx + target_len)]\n        return tf.reshape(audio, [target_len])\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(\n            tf.math.equal(max_val - min_val, 0),\n            spec - min_val,\n            (spec - min_val) / (max_val - min_val),\n        )\n        return spec\n\n    def get_target(target):\n        target = tf.reshape(target, [1])\n        target = tf.cast(tf.one_hot(target, CFG.num_classes), tf.float32)\n        target = tf.reshape(target, [CFG.num_classes])\n        return target\n\n    def decode(path):\n        # Load audio file\n        audio = get_audio(path)\n        # Crop or pad audio to keep a fixed length\n        audio = crop_or_pad(audio, dim)\n        # Audio to Spectrogram\n        spec = keras.layers.MelSpectrogram(\n            num_mel_bins=CFG.img_size[0],\n            fft_length=CFG.nfft,\n            sequence_stride=CFG.hop_length,\n            sampling_rate=CFG.sample_rate,\n        )(audio)\n        # Apply normalization and standardization\n        spec = apply_preproc(spec)\n        # Spectrogram to 3 channel image (for imagenet)\n        spec = tf.tile(spec[..., None], [1, 1, 3])\n        spec = tf.reshape(spec, [*CFG.img_size, 3])\n        return spec\n\n    def decode_with_labels(path, label):\n        label = get_target(label)\n        return decode(path), label\n\n    return decode_with_labels if with_labels else decode\n","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.782044Z","iopub.execute_input":"2024-06-17T04:33:30.782371Z","iopub.status.idle":"2024-06-17T04:33:30.799960Z","shell.execute_reply.started":"2024-06-17T04:33:30.782343Z","shell.execute_reply":"2024-06-17T04:33:30.798922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_augmenter():\n    augmenters = [\n        keras_cv.layers.MixUp(alpha=0.4),\n        keras_cv.layers.RandomCutout(height_factor=(1.0, 1.0),\n                                     width_factor=(0.06, 0.12)), # time-masking\n        keras_cv.layers.RandomCutout(height_factor=(0.06, 0.1),\n                                     width_factor=(1.0, 1.0)), # freq-masking\n    ]\n    \n    def augment(img, label):\n        data = {\"images\":img, \"labels\":label}\n        for augmenter in augmenters:\n            if tf.random.uniform([]) < 0.35:\n                data = augmenter(data, training=True)\n        return data[\"images\"], data[\"labels\"]\n    \n    return augment","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.800951Z","iopub.execute_input":"2024-06-17T04:33:30.801263Z","iopub.status.idle":"2024-06-17T04:33:30.812987Z","shell.execute_reply.started":"2024-06-17T04:33:30.801238Z","shell.execute_reply":"2024-06-17T04:33:30.812126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_dataset(paths, labels=None, batch_size=32, \n                  decode_fn=None, augment_fn=None, cache=True,\n                  augment=False, shuffle=2048):\n\n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None, dim=CFG.audio_len)\n\n    if augment_fn is None:\n        augment_fn = build_augmenter()\n        \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = (paths,) if labels is None else (paths, labels)\n    ds = tf.data.Dataset.from_tensor_slices(slices)\n    ds = ds.map(decode_fn, num_parallel_calls=AUTO)\n    ds = ds.cache() if cache else ds\n    if shuffle:\n        opt = tf.data.Options()\n        ds = ds.shuffle(shuffle, seed=CFG.seed)\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n    ds = ds.batch(batch_size, drop_remainder=True)\n    ds = ds.map(augment_fn, num_parallel_calls=AUTO) if augment else ds\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.814297Z","iopub.execute_input":"2024-06-17T04:33:30.814831Z","iopub.status.idle":"2024-06-17T04:33:30.824220Z","shell.execute_reply.started":"2024-06-17T04:33:30.814799Z","shell.execute_reply":"2024-06-17T04:33:30.823328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train\ntrain_paths = train_df.filepath.values\ntrain_labels = train_df.target.values\ntrain_ds = build_dataset(train_paths, train_labels, batch_size=CFG.batch_size,\n                         shuffle=True, augment=CFG.augment)\n\n# Valid\nvalid_paths = valid_df.filepath.values\nvalid_labels = valid_df.target.values\nvalid_ds = build_dataset(valid_paths, valid_labels, batch_size=CFG.batch_size,\n                         shuffle=False, augment=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:30.825405Z","iopub.execute_input":"2024-06-17T04:33:30.825696Z","iopub.status.idle":"2024-06-17T04:33:35.370556Z","shell.execute_reply.started":"2024-06-17T04:33:30.825672Z","shell.execute_reply":"2024-06-17T04:33:35.369552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n\n\nbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(None, None, 3))\n\n\nbase_model.trainable = True\n\n\nmodel = Sequential([\n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(512, activation='relu'),\n    Dropout(0.3),\n    Dense(256, activation='relu'),\n    Dropout(0.3),\n    Dense(CFG.num_classes, activation='softmax')\n])\n\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:35.371755Z","iopub.execute_input":"2024-06-17T04:33:35.372055Z","iopub.status.idle":"2024-06-17T04:33:37.780343Z","shell.execute_reply.started":"2024-06-17T04:33:35.372029Z","shell.execute_reply":"2024-06-17T04:33:37.779566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:37.781363Z","iopub.execute_input":"2024-06-17T04:33:37.781613Z","iopub.status.idle":"2024-06-17T04:33:37.804682Z","shell.execute_reply.started":"2024-06-17T04:33:37.781591Z","shell.execute_reply":"2024-06-17T04:33:37.803760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\n\ndef get_lr_callback(batch_size=8, mode='cos', epochs=10, plot=False):\n    lr_start, lr_max, lr_min = 5e-5, 8e-6 * batch_size, 1e-5\n    lr_ramp_ep, lr_sus_ep, lr_decay = 3, 0, 0.75\n\n    def lrfn(epoch):  # Learning rate update function\n        if epoch < lr_ramp_ep: lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n        elif epoch < lr_ramp_ep + lr_sus_ep: lr = lr_max\n        elif mode == 'exp': lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n        elif mode == 'step': lr = lr_max * lr_decay**((epoch - lr_ramp_ep - lr_sus_ep) // 2)\n        elif mode == 'cos':\n            decay_total_epochs, decay_epoch_index = epochs - lr_ramp_ep - lr_sus_ep + 3, epoch - lr_ramp_ep - lr_sus_ep\n            phase = math.pi * decay_epoch_index / decay_total_epochs\n            lr = (lr_max - lr_min) * 0.5 * (1 + math.cos(phase)) + lr_min\n        return lr\n\n    if plot:  # Plot lr curve if plot is True\n        plt.figure(figsize=(10, 5))\n        plt.plot(np.arange(epochs), [lrfn(epoch) for epoch in np.arange(epochs)], marker='o')\n        plt.xlabel('epoch'); plt.ylabel('lr')\n        plt.title('LR Scheduler')\n        plt.show()\n\n    return keras.callbacks.LearningRateScheduler(lrfn, verbose=False)  # Create lr callback","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:37.805954Z","iopub.execute_input":"2024-06-17T04:33:37.807233Z","iopub.status.idle":"2024-06-17T04:33:37.817854Z","shell.execute_reply.started":"2024-06-17T04:33:37.807206Z","shell.execute_reply":"2024-06-17T04:33:37.817040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr_cb = get_lr_callback(CFG.batch_size, plot=True)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:37.818999Z","iopub.execute_input":"2024-06-17T04:33:37.819297Z","iopub.status.idle":"2024-06-17T04:33:38.100539Z","shell.execute_reply.started":"2024-06-17T04:33:37.819269Z","shell.execute_reply":"2024-06-17T04:33:38.099600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ckpt_cb = keras.callbacks.ModelCheckpoint(\"best_model.weights.h5\",\n                                         monitor='accuracy',\n                                         save_best_only=True,\n                                         save_weights_only=True,\n                                         mode='max')","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:38.101557Z","iopub.execute_input":"2024-06-17T04:33:38.101811Z","iopub.status.idle":"2024-06-17T04:33:38.106256Z","shell.execute_reply.started":"2024-06-17T04:33:38.101787Z","shell.execute_reply":"2024-06-17T04:33:38.105205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_ds, \n    validation_data=valid_ds, \n    epochs=100,\n    callbacks=[lr_cb, ckpt_cb], \n    verbose=1\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T04:33:38.107413Z","iopub.execute_input":"2024-06-17T04:33:38.107691Z","iopub.status.idle":"2024-06-17T13:10:27.624853Z","shell.execute_reply.started":"2024-06-17T04:33:38.107667Z","shell.execute_reply":"2024-06-17T13:10:27.623945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-17T13:10:27.626162Z","iopub.execute_input":"2024-06-17T13:10:27.626460Z","iopub.status.idle":"2024-06-17T13:10:27.651256Z","shell.execute_reply.started":"2024-06-17T13:10:27.626435Z","shell.execute_reply":"2024-06-17T13:10:27.650170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_epoch = np.argmax(history.history[\"val_accuracy\"])\nbest_score = history.history[\"val_accuracy\"][best_epoch]\nprint('>>> Best accuracy: ', best_score)\nprint('>>> Best Epoch: ', best_epoch+1)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T13:16:17.679757Z","iopub.execute_input":"2024-06-17T13:16:17.680374Z","iopub.status.idle":"2024-06-17T13:16:17.686054Z","shell.execute_reply.started":"2024-06-17T13:16:17.680341Z","shell.execute_reply":"2024-06-17T13:16:17.685181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}