{"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":180330512,"sourceType":"kernelVersion"}],"dockerImageVersionId":30698,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\nimport 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":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-29T01:22:27.425660Z","iopub.execute_input":"2024-05-29T01:22:27.426867Z","iopub.status.idle":"2024-05-29T01:22:49.801366Z","shell.execute_reply.started":"2024-05-29T01:22:27.426825Z","shell.execute_reply":"2024-05-29T01:22:49.800082Z"},"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 = 5 # 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    \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-05-29T01:22:49.804288Z","iopub.execute_input":"2024-05-29T01:22:49.805156Z","iopub.status.idle":"2024-05-29T01:22:49.827152Z","shell.execute_reply.started":"2024-05-29T01:22:49.805112Z","shell.execute_reply":"2024-05-29T01:22:49.826019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = '/kaggle/input/birdclef-2024'","metadata":{"execution":{"iopub.status.busy":"2024-05-29T01:22:49.833935Z","iopub.execute_input":"2024-05-29T01:22:49.834339Z","iopub.status.idle":"2024-05-29T01:22:49.839451Z","shell.execute_reply.started":"2024-05-29T01:22:49.834297Z","shell.execute_reply":"2024-05-29T01:22:49.838251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.set_random_seed(CFG.seed)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T01:22:49.840859Z","iopub.execute_input":"2024-05-29T01:22:49.841197Z","iopub.status.idle":"2024-05-29T01:22:49.851272Z","shell.execute_reply.started":"2024-05-29T01:22:49.841170Z","shell.execute_reply":"2024-05-29T01:22:49.850080Z"},"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":{"execution":{"iopub.status.busy":"2024-05-29T01:22:49.852838Z","iopub.execute_input":"2024-05-29T01:22:49.853149Z","iopub.status.idle":"2024-05-29T01:22:50.000554Z","shell.execute_reply.started":"2024-05-29T01:22:49.853123Z","shell.execute_reply":"2024-05-29T01:22:49.999421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import InceptionV3\n# Create an input layer for the model\ninp = keras.layers.Input(shape=(None, None, 3))\nbackbone = InceptionV3(include_top=False, weights=None, input_tensor=inp, pooling='avg')\n\nx = keras.layers.Dense(128, activation='relu')(backbone.output)\nx = keras.layers.Dense(CFG.num_classes, activation='softmax', name='classifier')(x)\n\n# Build the model\nmodel = keras.models.Model(inputs=inp, outputs=x)\n\nmodel.load_weights(\"/kaggle/input/train-weight-inceptionv3/inception.weights.h5\")","metadata":{"execution":{"iopub.status.busy":"2024-05-29T01:22:50.002105Z","iopub.execute_input":"2024-05-29T01:22:50.002561Z","iopub.status.idle":"2024-05-29T01:22:53.530646Z","shell.execute_reply.started":"2024-05-29T01:22:50.002518Z","shell.execute_reply":"2024-05-29T01:22:53.529416Z"},"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":{"execution":{"iopub.status.busy":"2024-05-29T01:22:53.532994Z","iopub.execute_input":"2024-05-29T01:22:53.533438Z","iopub.status.idle":"2024-05-29T01:22:53.549835Z","shell.execute_reply.started":"2024-05-29T01:22:53.533398Z","shell.execute_reply":"2024-05-29T01:22:53.548549Z"},"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":{"execution":{"iopub.status.busy":"2024-05-29T01:22:53.552205Z","iopub.execute_input":"2024-05-29T01:22:53.552760Z","iopub.status.idle":"2024-05-29T01:22:53.566635Z","shell.execute_reply.started":"2024-05-29T01:22:53.552715Z","shell.execute_reply":"2024-05-29T01:22:53.565451Z"},"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":{"execution":{"iopub.status.busy":"2024-05-29T01:22:53.570087Z","iopub.execute_input":"2024-05-29T01:22:53.570622Z","iopub.status.idle":"2024-05-29T01:23:40.024766Z","shell.execute_reply.started":"2024-05-29T01:22:53.570589Z","shell.execute_reply":"2024-05-29T01:23:40.023707Z"},"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":{"execution":{"iopub.status.busy":"2024-05-29T01:23:40.026542Z","iopub.execute_input":"2024-05-29T01:23:40.027723Z","iopub.status.idle":"2024-05-29T01:23:40.339897Z","shell.execute_reply.started":"2024-05-29T01:23:40.027686Z","shell.execute_reply":"2024-05-29T01:23:40.338426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}