{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Introduction","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"This notebook introduces a simple way to prepare the data from the MP3 audio files before feeding it to an EfficientNet using Tensorflow 2.3 latest implementation. Please note that previous versions of this notebook prepared the data differently and used an LSTM but failed to demonstrated positive results. The model is then trained to classify one of the 264 birds. Please note that this is a work-in-progress and that I have made this code available solely to help everyone to get started with the competition. Of course, feel free to upvote this notebook if you find it useful!\n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"\n* **V9:** The entire pipeline now works from data preparation to model predictions and submission.\n* **V11:** As the model is failing to classify \"no call\" samples due to the lack of existing data, I am adding a check at prediction time. This check automatically classifies a sample as \"no call\" if none of the model's outputs are not activated with high confidence. *score: 0.50*\n* **V12:** Attempt to include all bird categories in the dataset/model and increase the confidence level required to take the model's output into account. *score: 0.54*\n* **V13:** The previous version taught us that the model did not learn to predict anything with high confidence. Therefore, this version will try to reduce the number of bird species being taught. The goal in this version is just to beat the baseline. *score: 0.53*\n* **V17:** Attempting classification of many bird species at the same time did not prove to be successful. In this version, we try to classify only 5 species while **all** other species will be categorised as other/nocall. \n* **V18:** We try to recognise 20 species instead of just 5 as V18 did not learn at all despite the use of class weights.\n* **V19:** While the previous notebooks had only a very simple data processing pipeline, we are now switching to using melspectrograms with an EfficientNet model.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"I started by installing Tensorflow 2.3 as I would like to use the new EfficientNet's implementation.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nos.listdir(\"/kaggle/input/tensorflow230\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install /kaggle/input/tensorflow230/tensorflow_estimator-2.3.0-py2.py3-none-any.whl\n!pip install /kaggle/input/tensorflow230/tensorflow-2.3.0rc2-cp37-cp37m-manylinux2010_x86_64.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip list | grep tensorflow","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport wave\nfrom scipy.io import wavfile\nimport os\nimport librosa\nfrom librosa.feature import melspectrogram\nimport warnings\nfrom sklearn.utils import shuffle\nfrom sklearn.utils import class_weight\nfrom PIL import Image\nfrom uuid import uuid4\nimport sklearn\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation\nfrom tensorflow.keras.layers import BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, LSTM, SimpleRNN, Conv1D, Input, BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB0\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data preparation","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"In this section, we first create two dictionaries to allow to translate each bird into an ID code and vice versa. As we won't be able to use the entirety of the data in this notebook for processing time reasons, we will shuffle the `DataFrame` with the training data before preparing the data. We will then create a new `DataFrame` where we will store all the samples, of 5 seconds each with a sampling rate of 10 data points per second.","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/birdsong-recognition/train.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It looks like each ebird is associated with a \"reasonable\" amount of samples. We only keep the bird species with 100 samples of the highest quality (4 or 5) to make the problem easier to start with.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df.query(\"rating>=4\")\n\nbirds_count = {}\nfor bird_species, count in zip(train_df.ebird_code.unique(), train_df.groupby(\"ebird_code\")[\"ebird_code\"].count().values):\n    birds_count[bird_species] = count\nmost_represented_birds = [key for key,value in birds_count.items() if value == 100]\n\ntrain_df = train_df.query(\"ebird_code in @most_represented_birds\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We now have only 49 bird species left in our dataset.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train_df.ebird_code.unique())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I will limit my classification problem to 20 birds to start.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"birds_to_recognise = sorted(shuffle(most_represented_birds)[:20])\nprint(birds_to_recognise)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = shuffle(train_df)\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_sample(filename, bird, output_folder):\n    wave_data, wave_rate = librosa.load(filename)\n    wave_data, _ = librosa.effects.trim(wave_data)\n    #only take 5s samples and add them to the dataframe\n    song_sample = []\n    sample_length = 5*wave_rate\n    samples_from_file = []\n    #The variable below is chosen mainly to create a 216x216 image\n    N_mels=216\n    for idx in range(0,len(wave_data),sample_length): \n        song_sample = wave_data[idx:idx+sample_length]\n        if len(song_sample)>=sample_length:\n            mel = melspectrogram(song_sample, n_mels=N_mels)\n            db = librosa.power_to_db(mel)\n            normalised_db = sklearn.preprocessing.minmax_scale(db)\n            filename = str(uuid4())+\".tif\"\n            db_array = (np.asarray(normalised_db)*255).astype(np.uint8)\n            db_image =  Image.fromarray(np.array([db_array, db_array, db_array]).T)\n            db_image.save(\"{}{}\".format(output_folder,filename))\n            \n            samples_from_file.append({\"song_sample\":\"{}{}\".format(output_folder,filename),\n                                            \"bird\":bird})\n    return samples_from_file","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The following cell will set all the samples with non-selected birds to the \"nocall\" ID code. This allows to focus on the classification of the 5 selected bird species while all of bird species will be categorised as \"nocall\".","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nwarnings.filterwarnings(\"ignore\")\nsamples_df = pd.DataFrame(columns=[\"song_sample\",\"bird\"])\n\n#We limit the number of audio files being sampled to 1000 in this notebook to save time\n#on top of having limited the number of bird species previously\nsample_limit = 1000\nsample_list = []\n\noutput_folder = \"/kaggle/working/melspectrogram_dataset/\"\nos.mkdir(output_folder)\nwith tqdm(total=sample_limit) as pbar:\n    for idx, row in train_df[:sample_limit].iterrows():\n        pbar.update(1)\n        try:\n            audio_file_path = \"/kaggle/input/birdsong-recognition/train_audio/\"\n            audio_file_path += row.ebird_code\n            \n            if row.ebird_code in birds_to_recognise:\n                sample_list += get_sample('{}/{}'.format(audio_file_path, row.filename), row.ebird_code, output_folder)\n            else:\n                sample_list += get_sample('{}/{}'.format(audio_file_path, row.filename), \"nocall\", output_folder)\n        except:\n            raise\n            print(\"{} is corrupted\".format(audio_file_path))\n            \nsamples_df = pd.DataFrame(sample_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"demo_img = Image.open(samples_df.iloc[0].song_sample)\nplt.imshow(demo_img)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"samples_df = shuffle(samples_df)\nsamples_df[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model creation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"training_percentage = 0.9\ntraining_item_count = int(len(samples_df)*training_percentage)\nvalidation_item_count = len(samples_df)-int(len(samples_df)*training_percentage)\ntraining_df = samples_df[:training_item_count]\nvalidation_df = samples_df[training_item_count:]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As shown in this [post](https://www.kaggle.com/c/birdsong-recognition/discussion/158943) by [Nanashi](https://www.kaggle.com/jesucristo), CNN-based models seem to outperform LSTM-based models for this type of tasks. Therefore, we will use the freshly added EfficientNet models from Tensorflow 2.3.0.\n\nAlso, I have realised that we can have several birds singing at the same time in our samples, which means that we will have to change the output layer and loss to have several possible outputs and not just one.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"classes_to_predict = sorted(samples_df.bird.unique())\ninput_shape = (216,216, 3)\neffnet_layers = EfficientNetB0(weights=None, include_top=False, input_shape=input_shape)\n\nfor layer in effnet_layers.layers:\n    layer.trainable = True\n\ndropout_dense_layer = 0.3\n\nmodel = Sequential()\nmodel.add(effnet_layers)\n    \nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(256, use_bias=False))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(dropout_dense_layer))\n\nmodel.add(Dense(len(classes_to_predict), activation=\"softmax\"))\n    \nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks = [ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1, factor=0.7),\n             EarlyStopping(monitor='val_loss', patience=5),\n             ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]\nmodel.compile(loss=\"categorical_crossentropy\", optimizer='adam')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_weights = class_weight.compute_class_weight(\"balanced\", classes_to_predict, samples_df.bird.values)\nclass_weights_dict = {i : class_weights[i] for i,label in enumerate(classes_to_predict)}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"training_batch_size = 32\nvalidation_batch_size = 32\ntarget_size = (216,216)\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1. / 255\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = training_df,\n    x_col='song_sample',\n    y_col='bird',\n    directory='/',\n    target_size=target_size,\n    batch_size=training_batch_size,\n    shuffle=True,\n    class_mode='categorical')\n\n\nvalidation_datagen = ImageDataGenerator(rescale=1. / 255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    dataframe = validation_df,\n    x_col='song_sample',\n    y_col='bird',\n    directory='/',\n    target_size=target_size,\n    shuffle=False,\n    batch_size=validation_batch_size,\n    class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model training","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"For now, I will comment out the class weights as I don't mind training a model that will be biased to \"nocall\".","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_generator,\n          epochs = 20, \n          validation_data=validation_generator,\n#           class_weight=class_weights_dict,\n          callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Loss over epochs')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='best')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Running predictions on a single batch from our validation set just to check if our model displays any anomalies.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict_generator(validation_generator)\nvalidation_df = pd.DataFrame(columns=[\"prediction\", \"groundtruth\", \"correct_prediction\"])\n\nfor pred, groundtruth in zip(preds[:16], validation_generator.__getitem__(0)[1]):\n    validation_df = validation_df.append({\"prediction\":classes_to_predict[np.argmax(pred)], \n                                       \"groundtruth\":classes_to_predict[np.argmax(groundtruth)], \n                                       \"correct_prediction\":np.argmax(pred)==np.argmax(groundtruth)}, ignore_index=True)\nvalidation_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf /kaggle/working/melspectrogram_dataset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"We load the weights for the best-performing model on our validation set.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(\"best_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As for the training samples, we will only load each audio file, generate a melspectrogram for each 5-second sequence and predict on it. This prediction function ensures that we do not reload the .mp3 audio file for every sample as it would significantly increase the processing time. Then, it adds all the predictions to the `test_df` DataFrame before generating the submission file.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict_on_melspectrogram(song_sample, sample_length):\n    N_mels=216\n\n    if len(song_sample)>=sample_length:\n        mel = melspectrogram(song_sample, n_mels=N_mels)\n        db = librosa.power_to_db(mel)\n        normalised_db = sklearn.preprocessing.minmax_scale(db)\n        db_array = (np.asarray(normalised_db)*255).astype(np.uint8)\n\n        prediction = model.predict(np.array([np.array([db_array, db_array, db_array]).T]))\n        predicted_bird = classes_to_predict[np.argmax(prediction)]\n        return predicted_bird\n    else:\n        return \"nocall\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict_submission(df, audio_file_path):\n        \n    loaded_audio_sample = []\n    previous_filename = \"\"\n    wave_data = []\n    wave_rate = None\n    sample_length = None\n    \n    for idx,row in df.iterrows():\n        #I added this exception as I've heard that some files may be corrupted.\n        try:\n            if previous_filename == \"\" or previous_filename!=row.audio_id:\n                filename = '{}/{}.mp3'.format(audio_file_path, row.audio_id)\n                wave_data, wave_rate = librosa.load(filename)\n                sample_length = 5*wave_rate\n            previous_filename = row.audio_id\n\n            #basically allows to check if we are running the examples or the test set.\n            if \"site\" in df.columns:\n                if row.site==\"site_1\" or row.site==\"site_2\":\n                    song_sample = np.array(wave_data[int(row.seconds-5)*wave_rate:int(row.seconds)*wave_rate])\n                elif row.site==\"site_3\":\n                    #for now, I only take the first 5s of the samples from site_3 as they are groundtruthed at file level\n                    song_sample = np.array(wave_data[0:sample_length])\n            else:\n                #same as the first condition but I isolated it for later and it is for the example file\n                song_sample = np.array(wave_data[int(row.seconds-5)*wave_rate:int(row.seconds)*wave_rate])\n            \n            predicted_bird = predict_on_melspectrogram(song_sample, sample_length)\n            df.at[idx,\"birds\"] = predicted_bird\n        except:\n            df.at[idx,\"birds\"] = \"nocall\"\n    return df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Below, We can test our prediction function using the examples provided.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"audio_file_path = \"/kaggle/input/birdsong-recognition/example_test_audio\"\nexample_df = pd.read_csv(\"/kaggle/input/birdsong-recognition/example_test_audio_summary.csv\")\n#Ajusting the example filenames and creating the audio_id column to match with the test file.\nexample_df[\"audio_id\"] = [ \"BLKFR-10-CPL_20190611_093000.pt540\" if filename==\"BLKFR-10-CPL\" else \"ORANGE-7-CAP_20190606_093000.pt623\" for filename in example_df[\"filename\"]]\n\nif os.path.exists(audio_file_path):\n    example_df = predict_submission(example_df, audio_file_path)\nexample_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_file_path = \"/kaggle/input/birdsong-recognition/test_audio\"\ntest_df = pd.read_csv(\"/kaggle/input/birdsong-recognition/test.csv\")\nsubmission_df = pd.read_csv(\"/kaggle/input/birdsong-recognition/sample_submission.csv\")\n\nif os.path.exists(test_file_path):\n    submission_df = predict_submission(test_df, test_file_path)\n\nsubmission_df[[\"row_id\",\"birds\"]].to_csv('submission.csv', index=False)\nsubmission_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Thanks for reading this notebook! If you found this notebook helpful, please give it an upvote. It is always greatly appreciated!","execution_count":null}],"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":4,"nbformat_minor":4}