{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Classify Species using De-noised Melspectrograms and a CNN\n\nHere I will be using my dataset (https://www.kaggle.com/tjcdev/rfcsaddenoisedmelspectrainv1) that was created by converting all the .flac files into de-noised melspectrogram images. \n\nThe following notebook contains the code for converting the .flac files into the de-noised melspectrograms https://www.kaggle.com/tjcdev/convert-audio-to-de-noised-melspectrogram-image"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\nimport pandas as pd\nimport numpy as np\n\nimport cv2\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout, GlobalMaxPooling2D\nfrom tensorflow.keras.models import Model\n\nfrom tqdm import tqdm\n\nfrom  matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"BASE_DIR = '../input/rfcsaddenoisedmelspectrainv1/train_images'\nOUTPUT_DIR = '.'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Create two arrays, one of images and one of the species in this image."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_fp = pd.read_csv('../input/rfcx-species-audio-detection/train_fp.csv')\ntrain_fp.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_SPECIES = len(set(train_fp['species_id'].values))\nprint('There are %s species' % (NUM_SPECIES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = []\nspecies = []\nfor index, row in tqdm(train_fp.iterrows()):    \n    # Load the image\n    IMG_HEIGHT = 310\n    IMG_WIDTH = 154\n    image_path= '%s/%s.jpg' % (BASE_DIR, str(row['recording_id']))\n    image= cv2.imread( image_path, cv2.COLOR_BGR2RGB)\n    image=cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH),interpolation = cv2.INTER_AREA)\n    image=np.array(image)\n    image = image.astype('float32')\n    image /= 255 \n    \n    # Put the image into an array\n    images = images + [image]\n    \n    # Put the species_id into an array\n    species = species + [int(row['species_id'])]\n\nspecies_dummies = pd.get_dummies(np.array(species))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"species_dummies","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"The image shapes are (154, 310, 3)."},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\n# Save Images Array\nimages_file = open('%s/images' % (OUTPUT_DIR), \"wb\")\nnp.save(images_file, images)\n# close the file\nimages_file.close\n\n# Save Species Array\nspecies_file = open('%s/species' % (OUTPUT_DIR), \"wb\")\nnp.save(species_file, species)\n# close the file\nspecies_file.close\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Compile and Fit Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the model using the functional API\ni = Input(shape=(IMG_HEIGHT,IMG_WIDTH, 3))\nx = Conv2D(32, (3, 3), strides=2, activation='relu')(i)\nx = Conv2D(64, (3, 3), strides=2, activation='relu')(x)\nx = Conv2D(128, (3, 3), strides=2, activation='relu')(x)\nx = Flatten()(x)\nx = Dropout(0.5)(x)\nx = Dense(1024, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(NUM_SPECIES, activation='softmax')(x)\n\nmodel = Model(i, x)\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x=np.array(images, np.float32), y=np.array(species_dummies, np.float32), epochs=15)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.predict(np.array(images[:2], np.float32))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Future Work\n\nNext I will build a prediction pipeline on the test set. In the meantime I hope this notebook is a helpful example of how to use the denoised melspectrogram dataset."},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}