{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Catboost Pipeline with Librosa Features\n\nIn this notebook I show how to train catboost classifier using tabular data representing the features of audio signals. You can find the code for generating these features [here](https://www.kaggle.com/vadimtimakin/librosa-feature-generation).\n\nI won't extract these features again here. They are already extracted and included in [this dataset](https://www.kaggle.com/vadimtimakin/librosa-features)."},{"metadata":{},"cell_type":"markdown","source":"### Set up the enviroment"},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"!pip install catboost","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom catboost import Pool, CatBoostClassifier\nfrom torch.nn import BCELoss","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Preparing data"},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"../input/librosa-features/train_with_features.csv\")\ndf.drop(['Unnamed: 0'], axis=1, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"columns =[\n    \"ebird_code\",\n    \"chroma_stft\",\n    \"spectral_centroid\",\n    \"spectral_bandwidth\",\n    \"spectral_rolloff\",\n    \"mfcc\",\n    \"chroma_cqt\",\n    \"chroma_cens\",\n    \"melspectrogram\",\n    \"spectral_contrast\",\n    \"poly_features\",\n    \"tonnetz\",\n    \"tempogram\",\n    \"fourier_tempogram\",\n    \"rms\",\n    \"zero_crossing_rate\",\n    \"spectral_flatness\",\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BIRD_CODE = {\n    'aldfly': 0, 'ameavo': 1, 'amebit': 2, 'amecro': 3, 'amegfi': 4,\n    'amekes': 5, 'amepip': 6, 'amered': 7, 'amerob': 8, 'amewig': 9,\n    'amewoo': 10, 'amtspa': 11, 'annhum': 12, 'astfly': 13, 'baisan': 14,\n    'baleag': 15, 'balori': 16, 'banswa': 17, 'barswa': 18, 'bawwar': 19,\n    'belkin1': 20, 'belspa2': 21, 'bewwre': 22, 'bkbcuc': 23, 'bkbmag1': 24,\n    'bkbwar': 25, 'bkcchi': 26, 'bkchum': 27, 'bkhgro': 28, 'bkpwar': 29,\n    'bktspa': 30, 'blkpho': 31, 'blugrb1': 32, 'blujay': 33, 'bnhcow': 34,\n    'boboli': 35, 'bongul': 36, 'brdowl': 37, 'brebla': 38, 'brespa': 39,\n    'brncre': 40, 'brnthr': 41, 'brthum': 42, 'brwhaw': 43, 'btbwar': 44,\n    'btnwar': 45, 'btywar': 46, 'buffle': 47, 'buggna': 48, 'buhvir': 49,\n    'bulori': 50, 'bushti': 51, 'buwtea': 52, 'buwwar': 53, 'cacwre': 54,\n    'calgul': 55, 'calqua': 56, 'camwar': 57, 'cangoo': 58, 'canwar': 59,\n    'canwre': 60, 'carwre': 61, 'casfin': 62, 'caster1': 63, 'casvir': 64,\n    'cedwax': 65, 'chispa': 66, 'chiswi': 67, 'chswar': 68, 'chukar': 69,\n    'clanut': 70, 'cliswa': 71, 'comgol': 72, 'comgra': 73, 'comloo': 74,\n    'commer': 75, 'comnig': 76, 'comrav': 77, 'comred': 78, 'comter': 79,\n    'comyel': 80, 'coohaw': 81, 'coshum': 82, 'cowscj1': 83, 'daejun': 84,\n    'doccor': 85, 'dowwoo': 86, 'dusfly': 87, 'eargre': 88, 'easblu': 89,\n    'easkin': 90, 'easmea': 91, 'easpho': 92, 'eastow': 93, 'eawpew': 94,\n    'eucdov': 95, 'eursta': 96, 'evegro': 97, 'fiespa': 98, 'fiscro': 99,\n    'foxspa': 100, 'gadwal': 101, 'gcrfin': 102, 'gnttow': 103, 'gnwtea': 104,\n    'gockin': 105, 'gocspa': 106, 'goleag': 107, 'grbher3': 108, 'grcfly': 109,\n    'greegr': 110, 'greroa': 111, 'greyel': 112, 'grhowl': 113, 'grnher': 114,\n    'grtgra': 115, 'grycat': 116, 'gryfly': 117, 'haiwoo': 118, 'hamfly': 119,\n    'hergul': 120, 'herthr': 121, 'hoomer': 122, 'hoowar': 123, 'horgre': 124,\n    'horlar': 125, 'houfin': 126, 'houspa': 127, 'houwre': 128, 'indbun': 129,\n    'juntit1': 130, 'killde': 131, 'labwoo': 132, 'larspa': 133, 'lazbun': 134,\n    'leabit': 135, 'leafly': 136, 'leasan': 137, 'lecthr': 138, 'lesgol': 139,\n    'lesnig': 140, 'lesyel': 141, 'lewwoo': 142, 'linspa': 143, 'lobcur': 144,\n    'lobdow': 145, 'logshr': 146, 'lotduc': 147, 'louwat': 148, 'macwar': 149,\n    'magwar': 150, 'mallar3': 151, 'marwre': 152, 'merlin': 153, 'moublu': 154,\n    'mouchi': 155, 'moudov': 156, 'norcar': 157, 'norfli': 158, 'norhar2': 159,\n    'normoc': 160, 'norpar': 161, 'norpin': 162, 'norsho': 163, 'norwat': 164,\n    'nrwswa': 165, 'nutwoo': 166, 'olsfly': 167, 'orcwar': 168, 'osprey': 169,\n    'ovenbi1': 170, 'palwar': 171, 'pasfly': 172, 'pecsan': 173, 'perfal': 174,\n    'phaino': 175, 'pibgre': 176, 'pilwoo': 177, 'pingro': 178, 'pinjay': 179,\n    'pinsis': 180, 'pinwar': 181, 'plsvir': 182, 'prawar': 183, 'purfin': 184,\n    'pygnut': 185, 'rebmer': 186, 'rebnut': 187, 'rebsap': 188, 'rebwoo': 189,\n    'redcro': 190, 'redhea': 191, 'reevir1': 192, 'renpha': 193, 'reshaw': 194,\n    'rethaw': 195, 'rewbla': 196, 'ribgul': 197, 'rinduc': 198, 'robgro': 199,\n    'rocpig': 200, 'rocwre': 201, 'rthhum': 202, 'ruckin': 203, 'rudduc': 204,\n    'rufgro': 205, 'rufhum': 206, 'rusbla': 207, 'sagspa1': 208, 'sagthr': 209,\n    'savspa': 210, 'saypho': 211, 'scatan': 212, 'scoori': 213, 'semplo': 214,\n    'semsan': 215, 'sheowl': 216, 'shshaw': 217, 'snobun': 218, 'snogoo': 219,\n    'solsan': 220, 'sonspa': 221, 'sora': 222, 'sposan': 223, 'spotow': 224,\n    'stejay': 225, 'swahaw': 226, 'swaspa': 227, 'swathr': 228, 'treswa': 229,\n    'truswa': 230, 'tuftit': 231, 'tunswa': 232, 'veery': 233, 'vesspa': 234,\n    'vigswa': 235, 'warvir': 236, 'wesblu': 237, 'wesgre': 238, 'weskin': 239,\n    'wesmea': 240, 'wessan': 241, 'westan': 242, 'wewpew': 243, 'whbnut': 244,\n    'whcspa': 245, 'whfibi': 246, 'whtspa': 247, 'whtswi': 248, 'wilfly': 249,\n    'wilsni1': 250, 'wiltur': 251, 'winwre3': 252, 'wlswar': 253, 'wooduc': 254,\n    'wooscj2': 255, 'woothr': 256, 'y00475': 257, 'yebfly': 258, 'yebsap': 259,\n    'yehbla': 260, 'yelwar': 261, 'yerwar': 262, 'yetvir': 263\n}\n\nINV_BIRD_CODE = {k: v for k, v in BIRD_CODE.items()}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"y = df.ebird_code.map(INV_BIRD_CODE)  # One-Hot encoding\ndf = df[columns]  # Leave features only \ndf['ebird_code'] = y  # Target data\nX = df.drop(['ebird_code'],axis=1)  # Train data\nprint(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"y","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Split the data into train and validation parts"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data, eval_data, train_label, eval_label = train_test_split(\n    X, y, test_size=0.2, random_state=42)\nprint(train_data.shape, eval_data.shape, train_label.shape, eval_label.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = Pool(data=train_data,\n                     label=train_label,\n                     )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"eval_dataset = Pool(data=eval_data,\n                    label=eval_label,\n                    )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Create and set up the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = CatBoostClassifier(iterations=100,\n                           learning_rate=0.003,\n                           depth=10,\n                           l2_leaf_reg = 0.01,\n                           loss_function='MultiClass')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_dataset)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_class = model.predict(eval_dataset)\nprint(preds_class)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = []\nfor i in range(len(preds_class)):\n    labels = list([0] * len(BIRD_CODE))\n    labels[preds_class[i][0]] = 1\n    labels = np.array(labels)\n    preds.append(labels)\npreds = np.array(preds)\n\nvalid_labels = []\nfor i in range(len(eval_label)):\n    labels = list([0] * len(BIRD_CODE))\n    labels[eval_label.iloc[i]] = 1\n    labels = np.array(labels)\n    valid_labels.append(labels)\nvalid_labels = np.array(valid_labels)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Counting the metric score"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn import metrics\n\nfbeta_sklearn = metrics.fbeta_score(valid_labels, preds, 2, average='samples')\nprint(fbeta_sklearn)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Saving the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_model(\"cbmodel.cbm\",\n           format=\"cbm\",\n           export_parameters=None,\n           pool=None)","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}