{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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 5GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport seaborn as sns\nimport librosa\nimport librosa.display\nfrom IPython import display\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom sklearn import metrics\nimport plotly.express as px\n\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/birdsong-recognition/train.csv')\nex_file = ('/kaggle/input/birdsong-recognition/train_audio'+ '/' + \n           train['ebird_code']+ '/' + \n           train['filename']).iloc[4423] #4423\nx, sr = librosa.load(ex_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bird_species_count = train['species'].value_counts(ascending=False)\nplt.xticks([])\nbird_species_count.plot()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"*Half of the species have 100 audio samples but about a quarter have less than 50*"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"np.random.seed(0)\n#sample_classes = len(train['species'].unique())\nsample_classes = 20\nsample_species = list(np.random.choice(train['species'].unique(), sample_classes, replace=False))\nbirdcall_meta_samp = train[(train['species'].isin(sample_species))]\n\nbirdcall_meta_samp.loc[:,'path'] = '/kaggle/input/birdsong-recognition/train_audio'+ '/' + birdcall_meta_samp['ebird_code'] + '/' + birdcall_meta_samp['filename']\nbirdcall_meta_samp.loc[:,'chunks'] = np.floor(birdcall_meta_samp['duration']/sample_classes).astype(int)\nbirdcall_meta_samp = birdcall_meta_samp[birdcall_meta_samp['chunks']>0]\nbirdcall_meta_samp = birdcall_meta_samp[birdcall_meta_samp['duration']<120]"},{"metadata":{"trusted":true},"cell_type":"code","source":"top_15 = list(train['country'].value_counts().head(15).reset_index()['index'])\ndata = train[train['country'].isin(top_15)]\n\nplt.figure(figsize=(16,6))\nax = sns.countplot(data['country'],palette = 'muted', order = data['country'].value_counts().index)\n\nplt.title('top 15 Countries with most Recordings', fontsize=15)\nplt.ylabel('Frequency',fontsize=13)\nplt.yticks(fontsize=12)\nplt.xticks(rotation=45,fontsize=12)\nplt.xlabel('')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = px.data.gapminder().query('year==2007')[['country','iso_alpha']]\n\ndata = pd.merge(left=train, right = df,how = 'inner',on='country')\n\ndata=data.groupby(by=['country','iso_alpha']).count()['species'].reset_index()\n\nfig = px.choropleth(data,locations = 'iso_alpha'\n                    ,color='species'\n                    ,hover_name = 'country'\n                    , color_continuous_scale = px.colors.sequential.Teal\n                    ,title='World: Recordings Per Country')\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"birdcall_meta_samp.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#quality rating for audio files\n\nrating = list(train['rating'].value_counts().reset_index()['index'])\nrating_data = train['rating']\n\nplt.figure(figsize=(16, 6))\nax = sns.countplot(train['rating'], palette=\"muted\", order = rating_data.value_counts().index.sort_values(ascending=False))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#distribution of audio duration\n\nplt.figure(figsize=(16, 6))\nduration = sns.distplot(train['duration'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"duration_adjusted = train['duration'][train['duration'].between(train['duration'].quantile(.05), train['duration'].quantile(.95))] \nplt.figure(figsize=(16, 6))\nduration = sns.distplot(duration_adjusted)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"map for audio recording by lat long"},{"metadata":{"trusted":true},"cell_type":"code","source":"speed = sns.countplot(train['speed'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"speed = sns.countplot(train['pitch'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"speed = sns.countplot(train['number_of_notes'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sample songs\n\nfiles = ('/kaggle/input/birdsong-recognition/train_audio'+ '/' + \n           train['ebird_code']+ '/' + \n           train['filename'])\nfiles_samp = files.sample(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = []\nsr = []\nfor i in files_samp:\n    a,b = librosa.load(i)\n    x.append(a)\n    sr.append(b)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display.Audio(data=x[0],rate=sr[0])\n#norpar/XC235682.mp3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display.Audio(data=x[1],rate=sr[1])\n#bkbwar/XC217955.mp3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display.Audio(data=x[2],rate=sr[2])\n#logshr/XC192339.mp3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nle = preprocessing.LabelEncoder()\nbirdcall_meta_samp['class_code'] = le.fit_transform(birdcall_meta_samp['ebird_code'])\nbirdcall_train, birdcall_test = train_test_split(birdcall_meta_samp, test_size=0.2, random_state=0, stratify=birdcall_meta_samp[['ebird_code']])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from scipy.ndimage.morphology import binary_erosion,binary_dilation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes_size = birdcall_train['ebird_code'].nunique()\n\nsec_split = 3\nobs_train = birdcall_train['chunks'].sum()\nobs_test = birdcall_test['chunks'].sum()\nclasses_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.zeros((obs_train, 128, 130))\nY_train = np.zeros((obs_train, classes_size))\nX_test = np.zeros((obs_test,128,130))\ny_test = np.zeros((obs_test,classes_size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler, MinMaxScaler\nscaler = StandardScaler()\n#minmaxscaler = MinMaxScaler()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def erosion(m):\n    norm_m=(m-m.min())/(m.max()-m.min())\n    column_medians=np.median(norm_m,axis=0)\n    row_medians=np.median(norm_m)\n    eroded_spectrogram = binary_erosion(np.greater(norm_m,column_medians*3)&np.greater(norm_m.T,row_medians*3).T*1)\n    return eroded_spectrogram\n\ndef dilation(x,e):\n    dilated = binary_dilation(e.sum(axis=0)>0,  iterations=3)\n    x = x[np.round(np.interp(np.arange(x.shape[0]),\n                             np.arange(dilated.shape[0])*x.shape[0]/dilated.shape[0],\n                             dilated)).astype(bool)]\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=0\n\nfor r in birdcall_train[['path','class_code']].iterrows():\n    # loading to lr\n    x, sr = librosa.load(r[1]['path'])\n    \n    S = librosa.feature.melspectrogram(x, sr=sr, n_fft=1028, hop_length=512, n_mels=128)\n    \n    #de-noising\n    \n    eroded_spec = erosion(S)\n    x = dilation(x,eroded_spec)\n    \n    window_slice = np.floor(x.shape[0]/sr/sec_split) # dividing the full length of the array divided by the sampling rate and pre-set sectional split of 3\n\n    x=x[:int(window_slice*sec_split*sr)] \n       ","execution_count":null,"outputs":[]},{"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}