{"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":"markdown","source":"# Prepare Enviroment ","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport math\n\nimport os\nimport cv2\n\nimport IPython.display as ipd \n\nimport librosa \nimport librosa.display\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import backend as K\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:17.061066Z","iopub.execute_input":"2022-04-13T06:29:17.061686Z","iopub.status.idle":"2022-04-13T06:29:23.731683Z","shell.execute_reply.started":"2022-04-13T06:29:17.061590Z","shell.execute_reply":"2022-04-13T06:29:23.730784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load DataFrame","metadata":{}},{"cell_type":"code","source":"train_path = '../input/freesound-audio-tagging/audio_train/'\n\nprint(len(os.listdir(train_path)))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:23.733344Z","iopub.execute_input":"2022-04-13T06:29:23.733603Z","iopub.status.idle":"2022-04-13T06:29:24.157638Z","shell.execute_reply.started":"2022-04-13T06:29:23.733566Z","shell.execute_reply":"2022-04-13T06:29:24.156889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"../input/freesound-audio-tagging/train.csv\")\n\nprint('The shape of the training data is: ', train.shape)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.158755Z","iopub.execute_input":"2022-04-13T06:29:24.159027Z","iopub.status.idle":"2022-04-13T06:29:24.186065Z","shell.execute_reply.started":"2022-04-13T06:29:24.158989Z","shell.execute_reply":"2022-04-13T06:29:24.185421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.188106Z","iopub.execute_input":"2022-04-13T06:29:24.188615Z","iopub.status.idle":"2022-04-13T06:29:24.205777Z","shell.execute_reply.started":"2022-04-13T06:29:24.188578Z","shell.execute_reply":"2022-04-13T06:29:24.205105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Unique Labels","metadata":{}},{"cell_type":"code","source":"uniq_labels = train.label.unique()\nprint('There are a total of', len(uniq_labels), 'unique labels.\\n')\nprint(uniq_labels)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.207011Z","iopub.execute_input":"2022-04-13T06:29:24.207245Z","iopub.status.idle":"2022-04-13T06:29:24.218038Z","shell.execute_reply.started":"2022-04-13T06:29:24.207197Z","shell.execute_reply":"2022-04-13T06:29:24.217264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label Distribution","metadata":{}},{"cell_type":"code","source":"print((train.manually_verified.value_counts() /len(train)).to_frame().T)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.219732Z","iopub.execute_input":"2022-04-13T06:29:24.220336Z","iopub.status.idle":"2022-04-13T06:29:24.232876Z","shell.execute_reply.started":"2022-04-13T06:29:24.220297Z","shell.execute_reply":"2022-04-13T06:29:24.232118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.manually_verified.value_counts().plot(kind='bar', xlabel='MGMT_value', ylabel='Count', \n                                     color=['#1E90FF', '#00C957'], edgecolor='black');","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.233912Z","iopub.execute_input":"2022-04-13T06:29:24.234764Z","iopub.status.idle":"2022-04-13T06:29:24.439652Z","shell.execute_reply.started":"2022-04-13T06:29:24.234729Z","shell.execute_reply":"2022-04-13T06:29:24.439006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Exploring Samples","metadata":{}},{"cell_type":"markdown","source":"## Sample 1","metadata":{}},{"cell_type":"code","source":"gunshot = '../input/freesound-audio-tagging/audio_train/0048fd00.wav'\nipd.Audio(gunshot)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.440833Z","iopub.execute_input":"2022-04-13T06:29:24.441687Z","iopub.status.idle":"2022-04-13T06:29:24.457480Z","shell.execute_reply.started":"2022-04-13T06:29:24.441646Z","shell.execute_reply":"2022-04-13T06:29:24.456873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"signal, sr = librosa.load(gunshot)\nprint(type(signal))\nprint(type(sr))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:24.458327Z","iopub.execute_input":"2022-04-13T06:29:24.458582Z","iopub.status.idle":"2022-04-13T06:29:25.445709Z","shell.execute_reply.started":"2022-04-13T06:29:24.458548Z","shell.execute_reply":"2022-04-13T06:29:25.444953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(signal.shape)\nprint(sr)\nprint(len(signal) / sr)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:25.448805Z","iopub.execute_input":"2022-04-13T06:29:25.449222Z","iopub.status.idle":"2022-04-13T06:29:25.454952Z","shell.execute_reply.started":"2022-04-13T06:29:25.449169Z","shell.execute_reply":"2022-04-13T06:29:25.454220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = [12,3])\nplt.subplot(2,1,1)\nplt.plot(signal)\nplt.subplot(2,1,2)\ninterval = range(2000, 3000)\nplt.plot(interval, signal[interval])\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:25.456220Z","iopub.execute_input":"2022-04-13T06:29:25.456645Z","iopub.status.idle":"2022-04-13T06:29:25.743653Z","shell.execute_reply.started":"2022-04-13T06:29:25.456608Z","shell.execute_reply":"2022-04-13T06:29:25.742989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x1 = librosa.feature.melspectrogram(y=signal, sr=22050)   \nx2 = librosa.power_to_db(x1, ref=np.max)   \n\nprint(x2.shape)\n\nlibrosa.display.specshow(x2, sr=22050, x_axis='time', y_axis='hz')\nplt.colorbar()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:25.744994Z","iopub.execute_input":"2022-04-13T06:29:25.745268Z","iopub.status.idle":"2022-04-13T06:29:26.019714Z","shell.execute_reply.started":"2022-04-13T06:29:25.745231Z","shell.execute_reply":"2022-04-13T06:29:26.019064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Sample 2","metadata":{}},{"cell_type":"code","source":"cello = '../input/freesound-audio-tagging/audio_train/0091fc7f.wav'\nipd.Audio(cello)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.020988Z","iopub.execute_input":"2022-04-13T06:29:26.021421Z","iopub.status.idle":"2022-04-13T06:29:26.047920Z","shell.execute_reply.started":"2022-04-13T06:29:26.021380Z","shell.execute_reply":"2022-04-13T06:29:26.047372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"signal, sr = librosa.load(cello)\nprint(type(signal))\nprint(type(sr))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.049034Z","iopub.execute_input":"2022-04-13T06:29:26.049395Z","iopub.status.idle":"2022-04-13T06:29:26.291824Z","shell.execute_reply.started":"2022-04-13T06:29:26.049360Z","shell.execute_reply":"2022-04-13T06:29:26.290910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(signal.shape)\nprint(sr)\nprint(len(signal) / sr)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.293284Z","iopub.execute_input":"2022-04-13T06:29:26.293559Z","iopub.status.idle":"2022-04-13T06:29:26.300030Z","shell.execute_reply.started":"2022-04-13T06:29:26.293521Z","shell.execute_reply":"2022-04-13T06:29:26.299231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = [12,3])\nplt.subplot(2,1,1)\nplt.plot(signal)\nplt.subplot(2,1,2)\ninterval = range(2000, 3000)\nplt.plot(interval, signal[interval])\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.301579Z","iopub.execute_input":"2022-04-13T06:29:26.301877Z","iopub.status.idle":"2022-04-13T06:29:26.629900Z","shell.execute_reply.started":"2022-04-13T06:29:26.301835Z","shell.execute_reply":"2022-04-13T06:29:26.629245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x1 = librosa.feature.melspectrogram(y=signal, sr=22050)   \nx2 = librosa.power_to_db(x1, ref=np.max)   \n\nprint(x2.shape)\n\nlibrosa.display.specshow(x2, sr=22050, x_axis='time', y_axis='hz')\nplt.colorbar()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.631386Z","iopub.execute_input":"2022-04-13T06:29:26.631670Z","iopub.status.idle":"2022-04-13T06:29:26.954632Z","shell.execute_reply.started":"2022-04-13T06:29:26.631630Z","shell.execute_reply":"2022-04-13T06:29:26.953992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Label Encoder","metadata":{}},{"cell_type":"code","source":"labels = np.unique(train.label.values)\nlabel_encoder = {label:i for i, label in enumerate(labels)}\nprint(label_encoder['Cello'])\nprint(label_encoder['Gunshot_or_gunfire'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.956112Z","iopub.execute_input":"2022-04-13T06:29:26.956618Z","iopub.status.idle":"2022-04-13T06:29:26.971239Z","shell.execute_reply.started":"2022-04-13T06:29:26.956579Z","shell.execute_reply":"2022-04-13T06:29:26.970246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Displaying Several Spectrogram Images","metadata":{}},{"cell_type":"code","source":"sample = train.sample(20)\n\nplt.figure(figsize=[20,9])\n\nfor i in range(20):\n    fname = train_path + sample.fname.iloc[i]\n    clip, sr = librosa.load(fname, sr=44100)\n    S1 = librosa.feature.melspectrogram(y=clip, sr=44100) \n    S2 = librosa.power_to_db(S1, ref=np.max)                \n    \n    plt.subplot(5, 4, i+1)\n    librosa.display.specshow(S2)\n    plt.title(f'{sample.label.iloc[i]} - {S2.shape[:2]} - {sample.fname.iloc[i]} ', color = \"white\")\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:26.972872Z","iopub.execute_input":"2022-04-13T06:29:26.973146Z","iopub.status.idle":"2022-04-13T06:29:30.125585Z","shell.execute_reply.started":"2022-04-13T06:29:26.973111Z","shell.execute_reply":"2022-04-13T06:29:30.121279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Generators","metadata":{}},{"cell_type":"code","source":"SPEC_PATH = '../input/freesound-melpec-128-512-2sec/spectrograms'\nIMG_SIZE = (128,32)\n\nclass DataGenerator(keras.utils.Sequence):\n    \n    def __init__(self, df, batch_size=32, shuffle=True, is_train=True):\n        self.df = df\n        self.n = len(df)\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.is_train = is_train\n        self.on_epoch_end()\n        \n    def on_epoch_end(self):\n        self.indices = np.arange(self.n)\n        if self.shuffle == True:\n            np.random.shuffle(self.indices)   \n    \n    def __len__(self):\n        \n        return math.ceil( self.n / self.batch_size )\n    \n    def __getitem__(self, batch_index):\n        \n        start = batch_index * self.batch_size\n        end = (batch_index + 1) * self.batch_size\n        \n        indices = self.indices[start:end]\n        \n        return self.__data_generation(indices)\n    \n    def __data_generation(self, batch_indices):\n        batch_size = len(batch_indices)\n        \n        X = np.zeros(shape=(batch_size, IMG_SIZE[0], IMG_SIZE[1], 3))\n        y = np.zeros(batch_size)\n        \n        for i, idx in enumerate(batch_indices):\n            FILE = self.df.fname.values[idx]\n            LABEL = self.df.label.values[idx]\n            \n            SET = 'train_spec' if self.is_train else 'test_spec'\n            path = f'{SPEC_PATH}/{SET}/{FILE[:-4]}.npy'\n\n            try:\n                data_array = np.load(path)\n                resized = cv2.resize(data_array, (IMG_SIZE[1], IMG_SIZE[0]))\n                \n                for j in range(3):\n                    X[i,:,:,j] = resized \n                \n            except:\n                print('skipped')\n\n            if self.is_train:\n                y[i] = label_encoder[LABEL]\n\n        if self.is_train:    \n            return X, y\n        return X\n\n    \nGENERATOR_TEST = True\n\nif GENERATOR_TEST:\n    temp_gen = DataGenerator(train, batch_size=8, shuffle=False)\n    X,y = temp_gen.__getitem__(0)\n\n    print(X.shape)\n    print(y)\n    \n    librosa.display.specshow(X[0, :, :, 0])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:30.127228Z","iopub.execute_input":"2022-04-13T06:29:30.127482Z","iopub.status.idle":"2022-04-13T06:29:30.297985Z","shell.execute_reply.started":"2022-04-13T06:29:30.127449Z","shell.execute_reply":"2022-04-13T06:29:30.297234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, valid_df = train_test_split(train, test_size=0.2, random_state=1, stratify=train.label)\n\nprint(train_df.shape)\nprint(valid_df.shape)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:30.303706Z","iopub.execute_input":"2022-04-13T06:29:30.304024Z","iopub.status.idle":"2022-04-13T06:29:30.344164Z","shell.execute_reply.started":"2022-04-13T06:29:30.303982Z","shell.execute_reply":"2022-04-13T06:29:30.343387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader = DataGenerator(train_df, batch_size=64, shuffle=True)\nvalid_loader = DataGenerator(valid_df, batch_size=64, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:30.348982Z","iopub.execute_input":"2022-04-13T06:29:30.349265Z","iopub.status.idle":"2022-04-13T06:29:30.361032Z","shell.execute_reply.started":"2022-04-13T06:29:30.349228Z","shell.execute_reply":"2022-04-13T06:29:30.359936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TR_STEPS = len(train_loader)\nVA_STEPS = len(valid_loader)\n\nprint(TR_STEPS)\nprint(VA_STEPS)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:30.362867Z","iopub.execute_input":"2022-04-13T06:29:30.369615Z","iopub.status.idle":"2022-04-13T06:29:30.376504Z","shell.execute_reply.started":"2022-04-13T06:29:30.369567Z","shell.execute_reply":"2022-04-13T06:29:30.375580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building CNN","metadata":{}},{"cell_type":"code","source":"VGG16_model = tf.keras.applications.VGG16(input_shape=(128,32,3),include_top=False, weights='imagenet')\nVGG16_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:30.378279Z","iopub.execute_input":"2022-04-13T06:29:30.379107Z","iopub.status.idle":"2022-04-13T06:29:33.986447Z","shell.execute_reply.started":"2022-04-13T06:29:30.379048Z","shell.execute_reply":"2022-04-13T06:29:33.985716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    VGG16_model,\n    \n    Flatten(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.35),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.35),\n    BatchNormalization(),\n    \n    Dense(32, activation='relu'),\n    Dropout(0.35),\n    BatchNormalization(),\n    \n    Dense(41, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:33.987599Z","iopub.execute_input":"2022-04-13T06:29:33.987837Z","iopub.status.idle":"2022-04-13T06:29:34.112298Z","shell.execute_reply.started":"2022-04-13T06:29:33.987803Z","shell.execute_reply":"2022-04-13T06:29:34.111508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train Network","metadata":{}},{"cell_type":"markdown","source":"## Training Run 1","metadata":{}},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:34.113699Z","iopub.execute_input":"2022-04-13T06:29:34.113939Z","iopub.status.idle":"2022-04-13T06:29:34.126875Z","shell.execute_reply.started":"2022-04-13T06:29:34.113897Z","shell.execute_reply":"2022-04-13T06:29:34.126225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh1 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 25, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:29:34.128384Z","iopub.execute_input":"2022-04-13T06:29:34.128953Z","iopub.status.idle":"2022-04-13T06:34:46.369779Z","shell.execute_reply.started":"2022-04-13T06:29:34.128903Z","shell.execute_reply":"2022-04-13T06:34:46.368875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def merge_history(hlist):\n    history = {}\n    for k in hlist[0].history.keys():\n        history[k] = sum([h.history[k] for h in hlist], [])\n    return history","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:34:46.374770Z","iopub.execute_input":"2022-04-13T06:34:46.375071Z","iopub.status.idle":"2022-04-13T06:34:46.380736Z","shell.execute_reply.started":"2022-04-13T06:34:46.375032Z","shell.execute_reply":"2022-04-13T06:34:46.379863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def vis_training(h, start=1):\n    epoch_range = range(start, len(h['loss'])+1)\n    s = slice(start-1, None)\n\n    plt.figure(figsize=[14,4])\n\n    n = int(len(h.keys()) / 2)\n\n    for i in range(n):\n        k = list(h.keys())[i]\n        plt.subplot(1,n,i+1)\n        plt.plot(epoch_range, h[k][s], label='Training')\n        plt.plot(epoch_range, h['val_' + k][s], label='Validation')\n        plt.xlabel('Epoch'); plt.ylabel(k); plt.title(k)\n        plt.grid()\n        plt.legend()\n\n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:34:46.382088Z","iopub.execute_input":"2022-04-13T06:34:46.382587Z","iopub.status.idle":"2022-04-13T06:34:46.393950Z","shell.execute_reply.started":"2022-04-13T06:34:46.382542Z","shell.execute_reply":"2022-04-13T06:34:46.393131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:34:46.395342Z","iopub.execute_input":"2022-04-13T06:34:46.395804Z","iopub.status.idle":"2022-04-13T06:34:46.745685Z","shell.execute_reply.started":"2022-04-13T06:34:46.395765Z","shell.execute_reply":"2022-04-13T06:34:46.745032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 2","metadata":{}},{"cell_type":"code","source":"K.set_value(cnn.optimizer.learning_rate, 0.0001)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:34:46.747018Z","iopub.execute_input":"2022-04-13T06:34:46.747500Z","iopub.status.idle":"2022-04-13T06:34:46.751911Z","shell.execute_reply.started":"2022-04-13T06:34:46.747463Z","shell.execute_reply":"2022-04-13T06:34:46.751267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 25, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:34:46.753246Z","iopub.execute_input":"2022-04-13T06:34:46.753720Z","iopub.status.idle":"2022-04-13T06:39:12.435036Z","shell.execute_reply.started":"2022-04-13T06:34:46.753684Z","shell.execute_reply":"2022-04-13T06:39:12.434348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def vis_training(h, start=1):\n    epoch_range = range(start, len(h['loss'])+1)\n    s = slice(start-1, None)\n\n    plt.figure(figsize=[14,4])\n\n    n = int(len(h.keys()) / 2)\n\n    for i in range(n):\n        k = list(h.keys())[i]\n        plt.subplot(1,n,i+1)\n        plt.plot(epoch_range, h[k][s], label='Training')\n        plt.plot(epoch_range, h['val_' + k][s], label='Validation')\n        plt.xlabel('Epoch'); plt.ylabel(k); plt.title(k)\n        plt.grid()\n        plt.legend()\n\n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:39:12.436422Z","iopub.execute_input":"2022-04-13T06:39:12.437135Z","iopub.status.idle":"2022-04-13T06:39:12.445723Z","shell.execute_reply.started":"2022-04-13T06:39:12.437097Z","shell.execute_reply":"2022-04-13T06:39:12.445102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:39:12.447167Z","iopub.execute_input":"2022-04-13T06:39:12.447427Z","iopub.status.idle":"2022-04-13T06:39:12.833550Z","shell.execute_reply.started":"2022-04-13T06:39:12.447392Z","shell.execute_reply":"2022-04-13T06:39:12.832788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 3 (Fine-Tuning)","metadata":{}},{"cell_type":"code","source":"VGG16_model.trainable = True","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:39:12.834849Z","iopub.execute_input":"2022-04-13T06:39:12.835237Z","iopub.status.idle":"2022-04-13T06:39:12.840347Z","shell.execute_reply.started":"2022-04-13T06:39:12.835189Z","shell.execute_reply":"2022-04-13T06:39:12.839249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.0001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:39:12.841717Z","iopub.execute_input":"2022-04-13T06:39:12.842055Z","iopub.status.idle":"2022-04-13T06:39:12.859506Z","shell.execute_reply.started":"2022-04-13T06:39:12.842017Z","shell.execute_reply":"2022-04-13T06:39:12.858738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh3 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 25, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:39:12.860811Z","iopub.execute_input":"2022-04-13T06:39:12.861039Z","iopub.status.idle":"2022-04-13T06:43:59.609788Z","shell.execute_reply.started":"2022-04-13T06:39:12.861008Z","shell.execute_reply":"2022-04-13T06:43:59.608912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2, h3])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:43:59.610999Z","iopub.execute_input":"2022-04-13T06:43:59.611249Z","iopub.status.idle":"2022-04-13T06:43:59.990718Z","shell.execute_reply.started":"2022-04-13T06:43:59.611212Z","shell.execute_reply":"2022-04-13T06:43:59.990070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_VGG16_v01.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:43:59.992074Z","iopub.execute_input":"2022-04-13T06:43:59.992542Z","iopub.status.idle":"2022-04-13T06:44:00.329905Z","shell.execute_reply.started":"2022-04-13T06:43:59.992504Z","shell.execute_reply":"2022-04-13T06:44:00.329118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Test DataFrame","metadata":{}},{"cell_type":"code","source":"test = pd.read_csv('../input/freesound-audio-tagging/sample_submission.csv')\n\ntest_loader = DataGenerator(test, batch_size=64, shuffle=False, is_train=False)\n\nprobs = cnn.predict(test_loader)\nprint(probs.shape)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:44:00.331344Z","iopub.execute_input":"2022-04-13T06:44:00.331591Z","iopub.status.idle":"2022-04-13T06:45:14.866147Z","shell.execute_reply.started":"2022-04-13T06:44:00.331556Z","shell.execute_reply":"2022-04-13T06:45:14.865317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:45:14.868397Z","iopub.execute_input":"2022-04-13T06:45:14.868820Z","iopub.status.idle":"2022-04-13T06:45:14.876735Z","shell.execute_reply.started":"2022-04-13T06:45:14.868780Z","shell.execute_reply":"2022-04-13T06:45:14.875889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submit Top 1 Prediction","metadata":{}},{"cell_type":"code","source":"submission_top1 = test.copy()\n\nN = len(test)\nfor i in range(N):\n    p = probs[i, :]\n    idx = np.argmax(p)\n    submission_top1.label[i] = labels[idx]\n\nsubmission_top1.to_csv('submission_top1.csv', index=False, header=True)\n\nsubmission_top1.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:45:14.877974Z","iopub.execute_input":"2022-04-13T06:45:14.878424Z","iopub.status.idle":"2022-04-13T06:45:15.634520Z","shell.execute_reply.started":"2022-04-13T06:45:14.878375Z","shell.execute_reply":"2022-04-13T06:45:15.633805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submit Top 3 Predictions","metadata":{}},{"cell_type":"code","source":"submission_top3 = test.copy()\n\nN = len(test)\nfor i in range(N):\n    p = probs[i, :]\n    idx = np.argsort(-p)[:3]\n    top3 = labels[idx]\n    submission_top3.label[i] = ' '.join(top3)\n\nsubmission_top3.to_csv('submission_top3.csv', index=False, header=True)\nsubmission_top3.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:45:15.636019Z","iopub.execute_input":"2022-04-13T06:45:15.636305Z","iopub.status.idle":"2022-04-13T06:45:16.539763Z","shell.execute_reply.started":"2022-04-13T06:45:15.636268Z","shell.execute_reply":"2022-04-13T06:45:16.539044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}