{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# BirdCLEF 2021 - Birdcall Identification","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"### Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\nimport pandas as pd\nimport librosa as lb\nimport numpy as np\n\nfrom sklearn.utils import shuffle\nfrom PIL import Image\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\n# Global vars\nRANDOM_SEED = 1337\nSAMPLE_RATE = 32000\nSIGNAL_LENGTH = 5 # seconds\nSPEC_SHAPE = (48, 128) # height x width\nFMIN = 500\nFMAX = 12500\nMAX_AUDIO_FILES = 1500","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:40.265477Z","iopub.execute_input":"2021-05-25T04:38:40.266118Z","iopub.status.idle":"2021-05-25T04:38:48.854363Z","shell.execute_reply.started":"2021-05-25T04:38:40.265993Z","shell.execute_reply":"2021-05-25T04:38:48.853481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/birdclef-2021/train_metadata.csv',)\ntrain = train.query('rating>=4')\n\nbirds_count = {}\nfor bird_species, count in zip(train.primary_label.unique(), \n                               train.groupby('primary_label')['primary_label'].count().values):\n    birds_count[bird_species] = count\nmost_represented_birds = [key for key,value in birds_count.items() if value >= 200] \n\nTRAIN = train.query('primary_label in @most_represented_birds')\nLABELS = sorted(TRAIN.primary_label.unique())\n\nprint('NUMBER OF SPECIES IN TRAIN DATA:', len(LABELS))\nprint('NUMBER OF SAMPLES IN TRAIN DATA:', len(TRAIN))\nprint('LABELS:', most_represented_birds)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:48.855782Z","iopub.execute_input":"2021-05-25T04:38:48.856408Z","iopub.status.idle":"2021-05-25T04:38:49.446791Z","shell.execute_reply.started":"2021-05-25T04:38:48.856362Z","shell.execute_reply":"2021-05-25T04:38:49.445655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:49.448504Z","iopub.execute_input":"2021-05-25T04:38:49.448804Z","iopub.status.idle":"2021-05-25T04:38:49.482259Z","shell.execute_reply.started":"2021-05-25T04:38:49.448775Z","shell.execute_reply":"2021-05-25T04:38:49.481257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# FINAL NUMBER OF AUDIO FILES\n\nTRAIN = shuffle(TRAIN, random_state=RANDOM_SEED)[:MAX_AUDIO_FILES]\n\ndef get_spectrograms(filepath, primary_label, output_dir):\n    sig, rate = lb.load(filepath, sr=SAMPLE_RATE, offset=None, duration=15)\n    \n    sig_splits = []\n    for i in range(0, len(sig), int(SIGNAL_LENGTH * SAMPLE_RATE)):\n        split = sig[i:i + int(SIGNAL_LENGTH * SAMPLE_RATE)]\n        \n        if len(split) < int(SIGNAL_LENGTH * SAMPLE_RATE):\n            break\n        \n        sig_splits.append(split)\n    \n    s_cnt = 0\n    saved_samples = []\n    for chunk in sig_splits:\n        \n        hop_length = int(SIGNAL_LENGTH * SAMPLE_RATE / (SPEC_SHAPE[1] - 1))\n        mel_spec = lb.feature.melspectrogram(y=chunk, \n                                                  sr=SAMPLE_RATE, \n                                                  n_fft=1024, \n                                                  hop_length=hop_length, \n                                                  n_mels=SPEC_SHAPE[0], \n                                                  fmin=FMIN, \n                                                  fmax=FMAX)\n    \n        mel_spec = lb.power_to_db(mel_spec, ref=np.max) \n        \n        mel_spec -= mel_spec.min()\n        mel_spec /= mel_spec.max()\n        \n        save_dir = os.path.join(output_dir, primary_label)\n        if not os.path.exists(save_dir):\n            os.makedirs(save_dir)\n        save_path = os.path.join(save_dir, filepath.rsplit(os.sep, 1)[-1].rsplit('.', 1)[0] + \n                                 '_' + str(s_cnt) + '.png')\n        im = Image.fromarray(mel_spec * 255.0).convert(\"L\")\n        im.save(save_path)\n        \n        saved_samples.append(save_path)\n        s_cnt += 1\n        \n        \n    return saved_samples\n\nprint('FINAL NUMBER OF AUDIO FILES IN TRAINING DATA:', len(TRAIN))\n","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:49.483875Z","iopub.execute_input":"2021-05-25T04:38:49.484244Z","iopub.status.idle":"2021-05-25T04:38:49.501835Z","shell.execute_reply.started":"2021-05-25T04:38:49.484176Z","shell.execute_reply":"2021-05-25T04:38:49.501029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(most_represented_birds))","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:49.503121Z","iopub.execute_input":"2021-05-25T04:38:49.503509Z","iopub.status.idle":"2021-05-25T04:38:49.516678Z","shell.execute_reply.started":"2021-05-25T04:38:49.503476Z","shell.execute_reply":"2021-05-25T04:38:49.515694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Parse audio files and extract training samples\ninput_dir = '../input/birdclef-2021/train_short_audio/'\noutput_dir = '../working/melspectrogram_dataset/'\nsamples = []\nwith tqdm(total=len(TRAIN)) as pbar:\n    for idx, row in TRAIN.iterrows():\n        pbar.update(1)\n        \n        if row.primary_label in most_represented_birds:\n            audio_file_path = os.path.join(input_dir, row.primary_label, row.filename)\n            samples += get_spectrograms(audio_file_path, row.primary_label, output_dir)\n            \nTRAIN_SPECS = shuffle(samples, random_state=RANDOM_SEED)\nprint('SUCCESSFULLY EXTRACTED {} SPECTROGRAMS'.format(len(TRAIN_SPECS)))","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:38:49.518241Z","iopub.execute_input":"2021-05-25T04:38:49.518535Z","iopub.status.idle":"2021-05-25T04:40:52.693871Z","shell.execute_reply.started":"2021-05-25T04:38:49.518507Z","shell.execute_reply":"2021-05-25T04:40:52.692628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the first 12 spectrograms of TRAIN_SPECS\nplt.figure(figsize=(15, 7))\nfor i in range(12):\n    spec = Image.open(TRAIN_SPECS[i])\n    plt.subplot(3, 4, i + 1)\n    plt.title(TRAIN_SPECS[i].split(os.sep)[-1])\n    plt.imshow(spec, origin='lower')","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:40:52.699337Z","iopub.execute_input":"2021-05-25T04:40:52.702413Z","iopub.status.idle":"2021-05-25T04:40:54.070866Z","shell.execute_reply.started":"2021-05-25T04:40:52.702337Z","shell.execute_reply":"2021-05-25T04:40:54.069882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_specs, train_labels = [], []\nwith tqdm(total=len(TRAIN_SPECS)) as pbar:\n    for path in TRAIN_SPECS:\n        pbar.update(1)\n\n        # Open image\n        spec = Image.open(path)\n\n        # Convert to numpy array\n        spec = np.array(spec, dtype='float32')\n        \n        # Normalize between 0.0 and 1.0\n        # and exclude samples with nan \n        spec -= spec.min()\n        spec /= spec.max()\n        if not spec.max() == 1.0 or not spec.min() == 0.0:\n            continue\n\n        # Add channel axis to 2D array\n        spec = np.expand_dims(spec, -1)\n\n        # Add new dimension for batch size\n        spec = np.expand_dims(spec, 0)\n\n        # Add to train data\n        if len(train_specs) == 0:\n            train_specs = spec\n        else:\n            train_specs = np.vstack((train_specs, spec))\n\n        # Add to label data\n        target = np.zeros((len(LABELS)), dtype='float32')\n        bird = path.split(os.sep)[-2]\n        target[LABELS.index(bird)] = 1.0\n        if len(train_labels) == 0:\n            train_labels = target\n        else:\n            train_labels = np.vstack((train_labels, target))","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:40:54.073955Z","iopub.execute_input":"2021-05-25T04:40:54.074413Z","iopub.status.idle":"2021-05-25T04:42:19.355096Z","shell.execute_reply.started":"2021-05-25T04:40:54.074370Z","shell.execute_reply":"2021-05-25T04:42:19.354016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.random.set_seed(RANDOM_SEED)\n\nmodel = tf.keras.Sequential([\n    \n    # First conv block\n    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', \n                           input_shape=(SPEC_SHAPE[0], SPEC_SHAPE[1], 1)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)),\n    \n    # Second conv block\n    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)), \n    \n    # Third conv block\n    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)), \n    \n    # Fourth conv block\n    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)),\n    \n    # Global pooling instead of flatten()\n    tf.keras.layers.GlobalAveragePooling2D(), \n    \n    # Dense block\n    tf.keras.layers.Dense(256, activation='relu'),   \n    tf.keras.layers.Dropout(0.5),  \n    tf.keras.layers.Dense(256, activation='relu'),   \n    tf.keras.layers.Dropout(0.5),\n    \n    # Classification layer\n    tf.keras.layers.Dense(len(LABELS), activation='softmax')\n])\nprint('MODEL HAS {} PARAMETERS.'.format(model.count_params()))","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:42:19.357210Z","iopub.execute_input":"2021-05-25T04:42:19.357507Z","iopub.status.idle":"2021-05-25T04:42:19.576955Z","shell.execute_reply.started":"2021-05-25T04:42:19.357478Z","shell.execute_reply":"2021-05-25T04:42:19.575705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001),\n              loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.01),\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:42:19.578407Z","iopub.execute_input":"2021-05-25T04:42:19.578736Z","iopub.status.idle":"2021-05-25T04:42:19.596325Z","shell.execute_reply.started":"2021-05-25T04:42:19.578704Z","shell.execute_reply":"2021-05-25T04:42:19.595306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', \n                                                  patience=2, \n                                                  verbose=1, \n                                                  factor=0.5),\n             tf.keras.callbacks.EarlyStopping(monitor='val_loss', \n                                              verbose=1,\n                                              patience=5),\n             tf.keras.callbacks.ModelCheckpoint(filepath='best_model.h5', \n                                                monitor='val_loss',\n                                                verbose=0,\n                                                save_best_only=True)]","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:42:19.597698Z","iopub.execute_input":"2021-05-25T04:42:19.597982Z","iopub.status.idle":"2021-05-25T04:42:19.607327Z","shell.execute_reply.started":"2021-05-25T04:42:19.597955Z","shell.execute_reply":"2021-05-25T04:42:19.605987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_specs, \n          train_labels,\n          batch_size=32,\n          validation_split=0.2,\n          callbacks=callbacks,\n          epochs=15)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:42:19.608749Z","iopub.execute_input":"2021-05-25T04:42:19.609130Z","iopub.status.idle":"2021-05-25T04:45:25.515185Z","shell.execute_reply.started":"2021-05-25T04:42:19.609099Z","shell.execute_reply":"2021-05-25T04:45:25.513938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the best checkpoint\nmodel = tf.keras.models.load_model('best_model.h5')\n\n# Pick a soundscape\nsoundscape_path = '../input/birdclef-2021/train_soundscapes/28933_SSW_20170408.ogg'\n\n# Open it with librosa\nsig, rate = lb.load(soundscape_path, sr=SAMPLE_RATE)\n\n# Store results so that we can analyze them later\ndata = {'row_id': [], 'prediction': [], 'score': []}\n\n# Split signal into 5-second chunks\n# Just like we did before (well, this could actually be a seperate function)\nsig_splits = []\nfor i in range(0, len(sig), int(SIGNAL_LENGTH * SAMPLE_RATE)):\n    split = sig[i:i + int(SIGNAL_LENGTH * SAMPLE_RATE)]\n\n    # End of signal?\n    if len(split) < int(SIGNAL_LENGTH * SAMPLE_RATE):\n        break\n\n    sig_splits.append(split)\n    \n# Get the spectrograms and run inference on each of them\n# This should be the exact same process as we used to\n# generate training samples!\nseconds, scnt = 0, 0\nfor chunk in sig_splits:\n    \n    # Keep track of the end time of each chunk\n    seconds += 5\n        \n    # Get the spectrogram\n    hop_length = int(SIGNAL_LENGTH * SAMPLE_RATE / (SPEC_SHAPE[1] - 1))\n    mel_spec = lb.feature.melspectrogram(y=chunk, \n                                              sr=SAMPLE_RATE, \n                                              n_fft=1024, \n                                              hop_length=hop_length, \n                                              n_mels=SPEC_SHAPE[0], \n                                              fmin=FMIN, \n                                              fmax=FMAX)\n\n    mel_spec = lb.power_to_db(mel_spec, ref=np.max) \n\n    # Normalize to match the value range we used during training.\n    # That's something you should always double check!\n    mel_spec -= mel_spec.min()\n    mel_spec /= mel_spec.max()\n    \n    # Add channel axis to 2D array\n    mel_spec = np.expand_dims(mel_spec, -1)\n\n    # Add new dimension for batch size\n    mel_spec = np.expand_dims(mel_spec, 0)\n    \n    # Predict\n    p = model.predict(mel_spec)[0]\n    \n    # Get highest scoring species\n    idx = p.argmax()\n    species = LABELS[idx]\n    score = p[idx]\n    \n    # Prepare submission entry\n    data['row_id'].append(soundscape_path.split(os.sep)[-1].rsplit('_', 1)[0] + \n                          '_' + str(seconds))    \n    \n    # Decide if it's a \"nocall\" or a species by applying a threshold\n    if score > 0.25:\n        data['prediction'].append(species)\n        scnt += 1\n    else:\n        data['prediction'].append('nocall')\n        \n    # Add the confidence score as well\n    data['score'].append(score)\n        \nprint('SOUNSCAPE ANALYSIS DONE. FOUND {} BIRDS.'.format(scnt))","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:45:25.516622Z","iopub.execute_input":"2021-05-25T04:45:25.516918Z","iopub.status.idle":"2021-05-25T04:45:37.308853Z","shell.execute_reply.started":"2021-05-25T04:45:25.516889Z","shell.execute_reply":"2021-05-25T04:45:37.307557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make a new data frame\nresults = pd.DataFrame(data, columns = ['row_id', 'prediction', 'score'])\n\n# Merge with ground truth so we can inspect\ngt = pd.read_csv('../input/birdclef-2021/train_soundscape_labels.csv',)\nresults = pd.merge(gt, results, on='row_id')\n\n# Let's look at the first 50 entries\nresults.head(50)","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:45:37.310823Z","iopub.execute_input":"2021-05-25T04:45:37.311437Z","iopub.status.idle":"2021-05-25T04:45:37.379993Z","shell.execute_reply.started":"2021-05-25T04:45:37.311380Z","shell.execute_reply":"2021-05-25T04:45:37.378558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%ls \"../input\"","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:54:58.615031Z","iopub.execute_input":"2021-05-25T04:54:58.615970Z","iopub.status.idle":"2021-05-25T04:54:59.406496Z","shell.execute_reply.started":"2021-05-25T04:54:58.615918Z","shell.execute_reply":"2021-05-25T04:54:59.404767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.read_csv('../input/birdclef-2021/sample_submission.csv').to_csv('my_output.csv')","metadata":{"execution":{"iopub.status.busy":"2021-05-25T04:56:14.422735Z","iopub.execute_input":"2021-05-25T04:56:14.423221Z","iopub.status.idle":"2021-05-25T04:56:14.451798Z","shell.execute_reply.started":"2021-05-25T04:56:14.423177Z","shell.execute_reply":"2021-05-25T04:56:14.450557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}