{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":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":{},"cell_type":"markdown","source":"<center> <h1>Feature Extraction - Species Audio Detection</h1> </center>"},{"metadata":{},"cell_type":"markdown","source":"<img src=\"https://miro.medium.com/max/759/1*7sKM9aECRmuoqTadCYVw9A.jpeg\"\n     alt=\"Feature Extraction - Species Audio Detection\"\n     style=\"float: center;\" />"},{"metadata":{},"cell_type":"markdown","source":"> Extraction of features is a very important part in analyzing and finding relations between different things. The data provided of audio cannot be understood by the models directly to convert them into an understandable format feature extraction is used. It is a process that explains most of the data but in an understandable way. Feature extraction is required for classification, prediction and recommendation algorithms."},{"metadata":{},"cell_type":"markdown","source":"### Loading an audio"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import librosa\nx , sr = librosa.load('/kaggle/input/rfcx-species-audio-detection/test/f401344d9.flac')\nprint(type(x), type(sr))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Playing sample audio"},{"metadata":{"trusted":true},"cell_type":"code","source":"import IPython.display as ipd\nipd.Audio('/kaggle/input/rfcx-species-audio-detection/test/f401344d9.flac')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#display waveform\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport librosa.display\nplt.figure(figsize=(14, 5))\nlibrosa.display.waveplot(x, sr=sr)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Spectogram"},{"metadata":{"trusted":true},"cell_type":"code","source":"#display Spectrogram\nX = librosa.stft(x)\nXdb = librosa.amplitude_to_db(abs(X))\nplt.figure(figsize=(14, 5))\nlibrosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz') \n#If to pring log of frequencies  \n#librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='log')\nplt.colorbar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Feature Extraction"},{"metadata":{},"cell_type":"markdown","source":"### Zero Crossing Rate\nThe zero crossing rate is the rate of sign-changes along a signal, i.e., the rate at which the signal changes from positive to negative or back. This feature has been used heavily in both speech recognition and music information retrieval."},{"metadata":{"trusted":true},"cell_type":"code","source":"x, sr = librosa.load(audio_path)\n#Plot the signal:\nplt.figure(figsize=(14, 5))\nlibrosa.display.waveplot(x, sr=sr)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Zooming in:\nHere we will zoom or print spectrum for 100 array columns only."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Zooming in\nn0 = 9000\nn1 = 9100\nplt.figure(figsize=(14, 5))\nplt.plot(x[n0:n1])\nplt.grid()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Spectral Centroid\nIt indicates where the ”centre of mass” for a sound is located and is calculated as the weighted mean of the frequencies present in the sound."},{"metadata":{"trusted":true},"cell_type":"code","source":"#spectral centroid -- centre of mass -- weighted mean of the frequencies present in the sound\nimport sklearn\nspectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\nspectral_centroids.shape\n# Computing the time variable for visualization\nframes = range(len(spectral_centroids))\nt = librosa.frames_to_time(frames)\n# Normalising the spectral centroid for visualisation\ndef normalize(x, axis=0):\n    return sklearn.preprocessing.minmax_scale(x, axis=axis)\n#Plotting the Spectral Centroid along the waveform\nlibrosa.display.waveplot(x, sr=sr, alpha=0.4)\nplt.plot(t, normalize(spectral_centroids), color='r')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Spectral Rolloff\nSpectral rolloff is the frequency below which a specified percentage of the total spectral energy, e.g. 85%, lies."},{"metadata":{"trusted":true},"cell_type":"code","source":"spectral_rolloff = librosa.feature.spectral_rolloff(x, sr=sr)[0]\nlibrosa.display.waveplot(x, sr=sr, alpha=0.4)\nplt.plot(t, normalize(spectral_rolloff), color='r')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### MFCC — Mel-Frequency Cepstral Coefficients\nThe mel frequency cepstral coefficients (MFCCs) of a signal are a small set of features (usually about 10–20) which concisely describe the overall shape of a spectral envelope."},{"metadata":{"trusted":true},"cell_type":"code","source":"mfccs = librosa.feature.mfcc(x, sr=sr)\nprint(mfccs.shape)\n#Displaying  the MFCCs:\nlibrosa.display.specshow(mfccs, sr=sr, x_axis='time')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Now, we have extracted the features of music signals. We can use this feature extracted in various use cases such as classification into different genres.**"},{"metadata":{},"cell_type":"markdown","source":"To be Continued..!!"}],"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}