{"cells":[{"metadata":{},"cell_type":"markdown","source":"## <font size='5' color='red'>Objective</font>\nIn this competition the researchers from Cornell Lab of Ornithology’s Center for Conservation Bioacoustics (CBC) wants the kaggle community to help them build an AI solution to identify bird species using their bird call audio.Birds are excellent indicators of deteriorating habitat quality and environmental pollution.If successful, your work will help researchers better understand changes in habitat quality, levels of pollution, and the effectiveness of restoration efforts.\n\n![](https://i.ytimg.com/vi/0LJY0a1dmhg/maxresdefault.jpg)","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='5' color='blue'>Contents</font> \n\n\n* [Basic Exploratory Data analysis](#1)  \n    * [Getting started]()\n    * [Bird species in data]()\n    * [Countries from which samples are taken]()\n    * [Dates on which samples are collected]()\n    * [Popular time of the day]()\n    * [Duration of samples]()\n    * [Pitch and Volume]()\n    * [Sampling rate]()\n    * [Channels]()\n \n \n* [Audio Data analysis](#2)   \n     * [Playing audio]()\n     * [Visualizing audio in 2D]()\n     * [Spectrogram analysis]()\n \n \n* [Feature Extraction](#3)    \n     * [Spectral Centroid]()\n     * [Spectral Bandwidth]()\n     * [Spectral Rolloff]()\n     * [Zero-Crossing Rate]()\n     * [Mel-Frequency Cepstral Coefficients(MFCCs)]()\n     * [Chroma feature]()\n     \n* [Compare sound features](#4)","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Importing Libraries</font><a id='1'></a>\n","execution_count":null},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"!pip install librosa","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"from plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nimport matplotlib.pyplot as plt\nimport IPython.display as ipd\nimport plotly.express as px\nimport librosa.display\nimport pandas as pd\nimport numpy as  np\nimport librosa\nimport warnings\nimport IPython\nimport os\n\nplt.style.use(\"ggplot\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"warnings.filterwarnings(action='ignore')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Getting a Basic Idea</font><a id='2'></a>\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain = pd.read_csv(\"../input/birdsong-recognition/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Train dataset has {} rows and {} columns\".format(*train.shape))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Bird Species</font>\n\nBird species name ( target col name )","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"There are {} unique species of birds in train dataset\".format(train.species.nunique()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"species=train.species.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nfig = go.Figure(data=[\n    go.Bar(y=species.values, x=species.index,marker_color='deeppink')\n])\n\nfig.update_layout(title='Distribution of Bird Species')\nfig.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- We can see that there is exactly 100 samples for almost half number of species.\n- The min number of samples is for `Redhead`,it has only 9 samples.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Country</font>\n\nCountry in which the observation is made","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"country = train.country.value_counts()[:20]\nfig = go.Figure(data=[\n    go.Bar(x=country.index, y=country.values,marker_color='deeppink')\n])\n\nfig.update_layout(title='Countries from which data is obtained')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- Most number of samples are taken from USA.\n- North American countries dominates the list.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Date</font>\nDate in which the observation is made","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 8))\ntrain['date'].value_counts().sort_index().plot(color='pink',alpha=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- Date starts from 1992 to 2019.\n- Most number of samples where taken between 2013-2015.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Time</font>\nTime of the day in which the observation is made (in 24hrs format)","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nhist_data = pd.to_datetime(train.time,errors='coerce').dropna().dt.hour.values.tolist()\nfig = go.Figure(data=[go.Histogram(x=hist_data, histnorm='probability',marker_color='deeppink')])\nfig.update_layout(title='Time of the day at which data is obtained')\n\nfig.show()\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- 8.00 am seems to the peak time of observation.\n- Most samples are recoring in the morning time.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Duration</font>\nDuration of the observation\n\n","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\n\nhist_data = train.duration.values.tolist()\nfig = go.Figure(data=[go.Histogram(x=hist_data,marker_color='deeppink')])\nfig.update_layout(title='Duration of the observation')\n\nfig.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Rating</font>\nRating given to the observation ( 0-5)","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nhist_data = train.rating.values.tolist()\nfig = go.Figure(data=[go.Histogram(x=hist_data,marker_color='deeppink')])\nfig.update_layout(title='Rating of the observation')\n\nfig.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Bird Seen</font>\nIf the bird was seen during the recording.","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']\ndf = train.bird_seen.value_counts()\nfig = px.pie(df,df.index,df.values,labels={'index':'Bird Seen'})\nfig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,\n                  marker=dict(colors=colors, line=dict(color='#000000', width=2)))\nfig.update_layout(title='Bird Seen')\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- 80% of time,the bird is visually seen while recoring the audio.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Pitch and Volume</font>\nPitch and Volume of the recording","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nfig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])\ndf = train.volume.value_counts()\nfig.add_trace(go.Pie(labels=df.index, values=df.values, name=\"Volume\"),\n              1, 1)\n\ndf = train.pitch.value_counts()\nfig.add_trace(go.Pie(labels=df.index ,values=df.values, name=\"Pitch\"),\n              1, 2)\n\n# Use `hole` to create a donut-like pie chart\nfig.update_traces(hole=.4, hoverinfo=\"label+percent+name\")\nfig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,\n                  marker=dict(colors=colors, line=dict(color='#000000', width=2)))\n\nfig.update_layout(\n    title_text=\"Volume and Pitch of Observation\",\n    # Add annotations in the center of the donut pies.\n    annotations=[dict(text='Volume', x=0.18, y=0.5, font_size=20, showarrow=False),\n                 dict(text='Pitch', x=0.82, y=0.5, font_size=20, showarrow=False)])\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Sampling rate</font>\nSampling rate (audio) Sampling rate or sampling frequency defines the number of samples per second.\n","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"rec = train.sampling_rate.value_counts()\nfig = go.Figure(data=[\n    go.Bar(x=rec.index, y=rec.values,marker_color='deeppink')\n])\n\nfig.update_layout(title='Top Recordists')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- 44kHz is the common sampling rate used.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## <font size='3' color='red'>Channel</font>\nChannel is the passage way a signal or data is transported.One Channel is usually referred to as mono, while more Channels could either indicate stereo, surround sound and the like.","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"rec = train.channels.value_counts()\nfig = go.Figure(data=[\n    go.Bar(x=rec.index, y=rec.values,marker_color='deeppink')\n])\n\nfig.update_layout(title='Top Recordists')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Length</font>\nlength of the the audio signal ","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df=train.length.value_counts()\nfig = px.pie(df,df.index,df.values,labels={'index':'length of audio'})\nfig.update_layout(title='Length of audio signal')\nfig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,\n                  marker=dict(colors=colors, line=dict(color='#000000', width=2)))\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Geographical Analysis</font>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df=train.groupby(['latitude','longitude'],as_index=False)['ebird_code'].agg('count')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"df=df[df.latitude!='Not specified']\nfig = go.Figure()\nfig.add_trace(go.Scattergeo(\n        lon = df['longitude'],\n        lat = df['latitude'],\n        text = df['ebird_code'],\n        marker = dict(\n            size = df['ebird_code'],\n            line_color='rgb(40,40,40)',\n            line_width=0.5,\n            sizemode = 'area'\n        )))\n\n\nfig.update_layout(\n        title_text = 'Bird Samples collected From Parts of World',\n        showlegend = True,\n        geo = dict(\n            landcolor = 'rgb(217, 217, 217)',\n        )\n    )\n\nfig.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"- Much of the bird samples are collected from USA,SO let's have a look at USA states","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### <font size='3' color='red'>Samples from USA</font>","execution_count":null},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = go.Figure()\nfig.add_trace(go.Scattergeo(\n        locationmode = 'USA-states',\n        lon = df['longitude'],\n        lat = df['latitude'],\n        text = df['ebird_code'],\n        marker = dict(\n            size = df['ebird_code'],\n            line_color='rgb(40,40,40)',\n            line_width=0.5,\n            sizemode = 'area'\n        )))\n\n\nfig.update_layout(\n        title_text = 'Bird Samples collected From USA',\n        showlegend = True,\n        geo = dict(\n            scope = 'usa',\n            landcolor = 'rgb(217, 217, 217)',\n        )\n    )\n\nfig.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Playing some audio</font><a id='2'></a>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"path=\"../input/birdsong-recognition/train_audio/\"\nbirds=train.ebird_code.unique()[:6]\nfile=train[train.ebird_code==birds[0]]['filename'][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nfor i in range(0,2):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    print(birds[i])\n    IPython.display.display(ipd.Audio(audio_path))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Visualizing Audio</font>","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"In this section,we will just visualize our audio signals in a 2D plot.","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nplt.figure(figsize=(17,20 ))\n\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,2,i+1)\n    x , sr = librosa.load(audio_path)\n    librosa.display.waveplot(x, sr=sr,color='r')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='red'>Spectrogram</font>\n\nA spectrogram is a visual way of representing the signal strength, or “loudness”, of a signal over time at various frequencies present in a particular waveform. Not only can one see whether there is more or less energy at, for example, 2 Hz vs 10 Hz, but one can also see how energy levels vary over time.A spectrogram is usually depicted as a heat map.","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(17,20 ))\n\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,2,i+1)\n    x , sr = librosa.load(audio_path)\n    x = librosa.stft(x)\n    Xdb = librosa.amplitude_to_db(abs(x))\n    librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    plt.colorbar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='5' color='blue'>Feature extraction from Audio signal</font><a id='3'></a>\n\n\nThe spectral features (frequency-based features), which are obtained by converting the time-based signal into the frequency domain using the Fourier Transform, like fundamental frequency, frequency components, spectral centroid, spectral flux, spectral density, spectral roll-off, etc.\n","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### <font size='4' color='red'>Spectral Centroid</font>\n\nThe spectral centroid indicates at which frequency the energy of a spectrum is centered upon or in other words It indicates where the ” center of mass” for a sound is located. This is like a weighted mean:\n![](https://miro.medium.com/max/710/1*DkT47WzLrjigT_KVhDoMuQ.png)\n\nwhere S(k) is the spectral magnitude at frequency bin k, f(k) is the frequency at bin k.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import sklearn\n# Normalising the spectral centroid for visualisation\ndef normalize(x, axis=0):\n    return sklearn.preprocessing.minmax_scale(x, axis=axis)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nplt.figure(figsize=(17,20 ))\n\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,2,i+1)\n    x , sr = librosa.load(audio_path)\n    spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\n    frames = range(len(spectral_centroids))\n    t = librosa.frames_to_time(frames)\n    librosa.display.waveplot(x, sr=sr, alpha=0.4)\n    plt.plot(t, normalize(spectral_centroids), color='b')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    \n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <font size='4' color='red'>Spectral Rolloff</font>\nIt is a measure of the shape of the signal. It represents the frequency at which high frequencies decline to 0. To obtain it, we have to calculate the fraction of bins in the power spectrum where 85% of its power is at lower frequencies.","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"plt.figure(figsize=(17,20 ))\n\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,3,i+1)\n    x , sr = librosa.load(audio_path)\n    spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\n    frames = range(len(spectral_centroids))\n    t = librosa.frames_to_time(frames)\n    spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]\n    librosa.display.waveplot(x, sr=sr, alpha=0.4)\n    plt.plot(t, normalize(spectral_rolloff), color='r')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###  <font size='4' color='red'>Spectral Bandwidth</font>\nThe spectral bandwidth is defined as the width of the band of light at one-half the peak maximum (or full width at half maximum [FWHM]) and is represented by the two vertical red lines and λSB on the wavelength axis.\n![](https://miro.medium.com/max/1030/1*oUtYY0-j6iEc78Dew3d0uA.png)","execution_count":null},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\nplt.figure(figsize=(17,20 ))\n\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,3,i+1)\n    x , sr = librosa.load(audio_path)\n    spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\n    frames = range(len(spectral_centroids))\n    t = librosa.frames_to_time(frames)\n    spectral_bandwidth_2 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr)[0]\n    spectral_bandwidth_3 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=3)[0]\n    spectral_bandwidth_4 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=4)[0]\n    librosa.display.waveplot(x, sr=sr, alpha=0.4)\n    plt.plot(t, normalize(spectral_bandwidth_2), color='r')\n    plt.plot(t, normalize(spectral_bandwidth_3), color='g')\n    plt.plot(t, normalize(spectral_bandwidth_4), color='y')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    plt.legend(('p = 2', 'p = 3', 'p = 4'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###  Zero-Crossing Rate\nA very simple way for measuring the smoothness of a signal is to calculate the number of zero-crossing within a segment of that signal. A voice signal oscillates slowly — for example, a 100 Hz signal will cross zero 100 per second — whereas an unvoiced fricative can have 3000 zero crossings per second.\n![](https://miro.medium.com/max/1400/1*E_XSqizmLNksjknrD8oV2w.png)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"x , sr = librosa.load(audio_path)\nplt.figure(figsize=(14, 5))\nlibrosa.display.waveplot(x, sr=sr)\n# 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":"Zooming in...","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"zero_crossings = librosa.zero_crossings(x[n0:n1], pad=False)\nprint(sum(zero_crossings))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are seven points in which the wave crosses zero.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### <font size='4' color='red'>Mel-Frequency Cepstral Coefficients(MFCCs)</font>\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. It models the characteristics of the human voice.\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(17, 20))\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,2,i+1)\n    x , sr = librosa.load(audio_path)\n    mfccs = librosa.feature.mfcc(x, sr=sr)\n    librosa.display.specshow(mfccs, sr=sr, x_axis='time')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### <font size='4' color='red'>Chroma feature</font>\nA chroma feature or vector is typically a 12-element feature vector indicating how much energy of each pitch class, {C, C#, D, D#, E, …, B}, is present in the signal. In short, It provides a robust way to describe a similarity measure between music pieces.\n\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(17, 20))\n\nfor i in range(0,6):\n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(6,3,i+1)\n    x , sr = librosa.load(audio_path)\n    chromagram = librosa.feature.chroma_stft(x, sr=sr)\n    librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', cmap='coolwarm')\n    plt.gca().set_title(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## <font size='4' color='blue'>Compare features for Species</font><a id='4'></a>","execution_count":null},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig=plt.figure(figsize=(15,15))\nk=1\nfor i in range(5):\n    \n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(5,3,k)\n    k+=1\n    x , sr = librosa.load(audio_path)\n    librosa.display.waveplot(x, sr=sr)\n    plt.gca().set_title('Spectral Centroid')\n    plt.gca().set_ylabel(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n\n    plt.subplot(5,3,k)\n    k+=1\n    spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\n    frames = range(len(spectral_centroids))\n    t = librosa.frames_to_time(frames)\n    spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]\n    librosa.display.waveplot(x, sr=sr, alpha=0.4)\n    plt.plot(t, normalize(spectral_rolloff), color='r')\n    plt.gca().set_title('Spectral Rolloff ')\n    plt.gca().get_xaxis().set_visible(False)\n\n    plt.subplot(5,3,k)\n    k+=1\n    #spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]\n    #frames = range(len(spectral_centroids))\n    #t = librosa.frames_to_time(frames)\n    spectral_bandwidth_2 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr)[0]\n    spectral_bandwidth_3 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=3)[0]\n    spectral_bandwidth_4 = librosa.feature.spectral_bandwidth(x+0.01, sr=sr, p=4)[0]\n    librosa.display.waveplot(x, sr=sr, alpha=0.4)\n    plt.plot(t, normalize(spectral_bandwidth_2), color='r')\n    plt.plot(t, normalize(spectral_bandwidth_3), color='g')\n    plt.plot(t, normalize(spectral_bandwidth_4), color='y')\n    plt.gca().set_title('Spectral Bandwidth')\n    plt.gca().get_xaxis().set_visible(False)\n    plt.legend(('p = 2', 'p = 3', 'p = 4'))\n\n    \n#plt.gca().set_title('Comparing audio features for bird species')\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now,let's compare spectrogram,MFFC feature and chroma feature for some bird species.","execution_count":null},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig=plt.figure(figsize=(15,15))\nk=1\nfor i in range(5):\n    \n    file=train[train.ebird_code==birds[i]]['filename'].values[0]\n    audio_path=os.path.join(path,birds[i],file)\n    plt.subplot(5,3,k)\n    k+=1\n    x , sr = librosa.load(audio_path)\n    s = librosa.stft(x)\n    Xdb = librosa.amplitude_to_db(abs(s))\n    librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')\n    plt.gca().set_title('Spectrogram')\n    plt.gca().set_ylabel(birds[i])\n    plt.gca().get_xaxis().set_visible(False)\n\n    plt.subplot(5,3,k)\n    k+=1\n    mfccs = librosa.feature.mfcc(x, sr=sr)\n    librosa.display.specshow(mfccs, sr=sr, x_axis='time')\n    plt.gca().set_title('MFFC features ')\n    plt.gca().get_xaxis().set_visible(False)\n\n    plt.subplot(5,3,k)\n    k+=1\n    chromagram = librosa.feature.chroma_stft(x, sr=sr)\n    librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', cmap='coolwarm')\n    plt.gca().set_title('Chroma feature')\n    plt.gca().get_xaxis().set_visible(False)\n  \n\n    \n#fig.suptitle('Comparing audio features for bird species')\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"\n<font size='5' color='blue'>Leave an upvote if you think this was helpful!</font>","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}