{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import math, os, re, warnings, random\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport tensorflow.io\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\nfrom IPython.display import Audio\nfrom tensorflow.keras import Model, layers\nfrom sklearn.model_selection import KFold\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Input, Dense, Dropout, GaussianNoise\nfrom tensorflow.keras.applications import ResNet50\n# import efficientnet.keras as efn\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-25T16:12:46.657347Z","iopub.execute_input":"2021-11-25T16:12:46.657673Z","iopub.status.idle":"2021-11-25T16:12:46.665265Z","shell.execute_reply.started":"2021-11-25T16:12:46.657643Z","shell.execute_reply":"2021-11-25T16:12:46.664503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"traindf = pd.read_csv(r'../input/rfcx-species-audio-detection/train_tp.csv')\ntraindf.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-25T16:12:46.666691Z","iopub.execute_input":"2021-11-25T16:12:46.666905Z","iopub.status.idle":"2021-11-25T16:12:46.706109Z","shell.execute_reply.started":"2021-11-25T16:12:46.666879Z","shell.execute_reply":"2021-11-25T16:12:46.705189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def _bytes_feature(value):\n    \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n    if isinstance(value, type(tf.constant(0))):\n        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _float_feature(value):\n    \"\"\"Returns a float_list from a float / double.\"\"\"\n    return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef serialize_example(wav, recording_id, target, song_id, tmin,fmin, tmax, fmax):\n    feature = {\n      'wav': _bytes_feature(wav),\n      'recording_id': _bytes_feature(recording_id),\n      'target': _float_feature(target),\n      'song_id': _float_feature(song_id),\n      'tmin': _float_feature(tmin),\n      'fmin' : _float_feature(fmin),\n      'tmax': _float_feature(tmax),\n      'fmax' : _float_feature(fmax),\n    }\n    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n    return example_proto.SerializeToString() \n","metadata":{"execution":{"iopub.status.busy":"2021-11-25T16:12:46.709203Z","iopub.execute_input":"2021-11-25T16:12:46.709472Z","iopub.status.idle":"2021-11-25T16:12:46.719209Z","shell.execute_reply.started":"2021-11-25T16:12:46.709438Z","shell.execute_reply":"2021-11-25T16:12:46.718198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\n\ntfrec_num = 0\nkfold = StratifiedKFold(n_splits=10, shuffle=False)\nfor fold, (train_idx, test_idx) in enumerate(kfold.split(traindf['recording_id'], traindf['species_id'])):\n    x_train , y_train = traindf['recording_id'][test_idx] , traindf['species_id'][test_idx]\n   \n    with tf.io.TFRecordWriter('tp%.2i-%.2i.tfrec'%(tfrec_num, len(test_idx))) as writer:\n        print('Writing_tfrecords ',fold)\n        for recording_id , true_value in zip(x_train, y_train): \n            wav, _ = librosa.load(f'../input/rfcx-species-audio-detection/train/{recording_id}.flac', sr = None)\n            label_info = traindf.loc[traindf['recording_id'] == str(recording_id)].values[0]\n            wav = tf.audio.encode_wav(tf.reshape(wav,(wav.shape[0], 1)) ,sample_rate = 48000)\n            recording_id = label_info[0].encode()\n            target = label_info[1]\n            song_id = label_info[2]\n            tmin = label_info[3]\n            fmin = label_info[4]\n            tmax = label_info[5]\n            fmax = label_info[6]\n            example = serialize_example(wav, recording_id, target, song_id, tmin,fmin, tmax, fmax)\n            writer.write(example)\n    tfrec_num += 1\n","metadata":{"execution":{"iopub.status.busy":"2021-11-25T16:12:46.721252Z","iopub.execute_input":"2021-11-25T16:12:46.721605Z","iopub.status.idle":"2021-11-25T16:12:49.249492Z","shell.execute_reply.started":"2021-11-25T16:12:46.721565Z","shell.execute_reply":"2021-11-25T16:12:49.248233Z"},"trusted":true},"execution_count":null,"outputs":[]}]}