{"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-13T08:59:50.049018Z","iopub.execute_input":"2022-04-13T08:59:50.049551Z","iopub.status.idle":"2022-04-13T08:59:52.345607Z","shell.execute_reply.started":"2022-04-13T08:59:50.049467Z","shell.execute_reply":"2022-04-13T08:59:52.344737Z"},"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-13T08:59:52.347034Z","iopub.execute_input":"2022-04-13T08:59:52.347290Z","iopub.status.idle":"2022-04-13T08:59:52.358738Z","shell.execute_reply.started":"2022-04-13T08:59:52.347254Z","shell.execute_reply":"2022-04-13T08:59:52.357642Z"},"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-13T08:59:52.359889Z","iopub.execute_input":"2022-04-13T08:59:52.360212Z","iopub.status.idle":"2022-04-13T08:59:52.377893Z","shell.execute_reply.started":"2022-04-13T08:59:52.360157Z","shell.execute_reply":"2022-04-13T08:59:52.377131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T08:59:52.380314Z","iopub.execute_input":"2022-04-13T08:59:52.380786Z","iopub.status.idle":"2022-04-13T08:59:52.393106Z","shell.execute_reply.started":"2022-04-13T08:59:52.380749Z","shell.execute_reply":"2022-04-13T08:59:52.392396Z"},"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-13T08:59:52.394640Z","iopub.execute_input":"2022-04-13T08:59:52.395197Z","iopub.status.idle":"2022-04-13T08:59:52.403298Z","shell.execute_reply.started":"2022-04-13T08:59:52.395135Z","shell.execute_reply":"2022-04-13T08:59:52.402048Z"},"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-13T08:59:52.404353Z","iopub.execute_input":"2022-04-13T08:59:52.404965Z","iopub.status.idle":"2022-04-13T08:59:52.414573Z","shell.execute_reply.started":"2022-04-13T08:59:52.404930Z","shell.execute_reply":"2022-04-13T08:59:52.413222Z"},"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-13T08:59:52.416193Z","iopub.execute_input":"2022-04-13T08:59:52.416457Z","iopub.status.idle":"2022-04-13T08:59:52.601873Z","shell.execute_reply.started":"2022-04-13T08:59:52.416421Z","shell.execute_reply":"2022-04-13T08:59:52.601214Z"},"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-13T08:59:52.602983Z","iopub.execute_input":"2022-04-13T08:59:52.603248Z","iopub.status.idle":"2022-04-13T08:59:52.613332Z","shell.execute_reply.started":"2022-04-13T08:59:52.603211Z","shell.execute_reply":"2022-04-13T08:59:52.612606Z"},"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-13T08:59:52.614349Z","iopub.execute_input":"2022-04-13T08:59:52.614604Z","iopub.status.idle":"2022-04-13T08:59:53.322616Z","shell.execute_reply.started":"2022-04-13T08:59:52.614568Z","shell.execute_reply":"2022-04-13T08:59:53.321862Z"},"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-13T08:59:53.323924Z","iopub.execute_input":"2022-04-13T08:59:53.324165Z","iopub.status.idle":"2022-04-13T08:59:53.330777Z","shell.execute_reply.started":"2022-04-13T08:59:53.324134Z","shell.execute_reply":"2022-04-13T08:59:53.330103Z"},"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-13T08:59:53.332039Z","iopub.execute_input":"2022-04-13T08:59:53.332580Z","iopub.status.idle":"2022-04-13T08:59:53.607899Z","shell.execute_reply.started":"2022-04-13T08:59:53.332536Z","shell.execute_reply":"2022-04-13T08:59:53.607238Z"},"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-13T08:59:53.609107Z","iopub.execute_input":"2022-04-13T08:59:53.609491Z","iopub.status.idle":"2022-04-13T08:59:53.879751Z","shell.execute_reply.started":"2022-04-13T08:59:53.609454Z","shell.execute_reply":"2022-04-13T08:59:53.879009Z"},"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-13T08:59:53.883406Z","iopub.execute_input":"2022-04-13T08:59:53.883599Z","iopub.status.idle":"2022-04-13T08:59:53.901387Z","shell.execute_reply.started":"2022-04-13T08:59:53.883574Z","shell.execute_reply":"2022-04-13T08:59:53.900768Z"},"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-13T08:59:53.902555Z","iopub.execute_input":"2022-04-13T08:59:53.902933Z","iopub.status.idle":"2022-04-13T08:59:54.116053Z","shell.execute_reply.started":"2022-04-13T08:59:53.902898Z","shell.execute_reply":"2022-04-13T08:59:54.115361Z"},"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-13T08:59:54.117296Z","iopub.execute_input":"2022-04-13T08:59:54.117670Z","iopub.status.idle":"2022-04-13T08:59:54.123748Z","shell.execute_reply.started":"2022-04-13T08:59:54.117632Z","shell.execute_reply":"2022-04-13T08:59:54.123003Z"},"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-13T08:59:54.125224Z","iopub.execute_input":"2022-04-13T08:59:54.125727Z","iopub.status.idle":"2022-04-13T08:59:54.438727Z","shell.execute_reply.started":"2022-04-13T08:59:54.125692Z","shell.execute_reply":"2022-04-13T08:59:54.438007Z"},"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-13T08:59:54.439967Z","iopub.execute_input":"2022-04-13T08:59:54.440731Z","iopub.status.idle":"2022-04-13T08:59:54.748638Z","shell.execute_reply.started":"2022-04-13T08:59:54.440691Z","shell.execute_reply":"2022-04-13T08:59:54.748036Z"},"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-13T08:59:54.749832Z","iopub.execute_input":"2022-04-13T08:59:54.750537Z","iopub.status.idle":"2022-04-13T08:59:54.765150Z","shell.execute_reply.started":"2022-04-13T08:59:54.750499Z","shell.execute_reply":"2022-04-13T08:59:54.764191Z"},"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-13T08:59:54.766337Z","iopub.execute_input":"2022-04-13T08:59:54.767122Z","iopub.status.idle":"2022-04-13T08:59:57.768913Z","shell.execute_reply.started":"2022-04-13T08:59:54.767084Z","shell.execute_reply":"2022-04-13T08:59:57.768235Z"},"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-13T08:59:57.770164Z","iopub.execute_input":"2022-04-13T08:59:57.770625Z","iopub.status.idle":"2022-04-13T08:59:57.895676Z","shell.execute_reply.started":"2022-04-13T08:59:57.770585Z","shell.execute_reply":"2022-04-13T08:59:57.894774Z"},"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-13T08:59:57.897314Z","iopub.execute_input":"2022-04-13T08:59:57.897581Z","iopub.status.idle":"2022-04-13T08:59:57.929108Z","shell.execute_reply.started":"2022-04-13T08:59:57.897543Z","shell.execute_reply":"2022-04-13T08:59:57.928440Z"},"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-13T08:59:57.930528Z","iopub.execute_input":"2022-04-13T08:59:57.930984Z","iopub.status.idle":"2022-04-13T08:59:57.935487Z","shell.execute_reply.started":"2022-04-13T08:59:57.930948Z","shell.execute_reply":"2022-04-13T08:59:57.934636Z"},"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-13T08:59:57.936591Z","iopub.execute_input":"2022-04-13T08:59:57.936896Z","iopub.status.idle":"2022-04-13T08:59:57.949077Z","shell.execute_reply.started":"2022-04-13T08:59:57.936862Z","shell.execute_reply":"2022-04-13T08:59:57.948031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building CNN","metadata":{}},{"cell_type":"code","source":"VGG19_model = tf.keras.applications.VGG19(input_shape=(128,32,3),include_top=False, weights='imagenet')\nVGG19_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-04-13T08:59:57.950936Z","iopub.execute_input":"2022-04-13T08:59:57.951533Z","iopub.status.idle":"2022-04-13T08:59:59.272408Z","shell.execute_reply.started":"2022-04-13T08:59:57.951491Z","shell.execute_reply":"2022-04-13T08:59:59.271636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    VGG19_model,\n    \n    Flatten(),\n    \n    Dense(256, activation='relu'),\n    Dropout(0.4),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.4),\n    BatchNormalization(),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.4),\n    BatchNormalization(),\n    \n    Dense(41, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T08:59:59.273636Z","iopub.execute_input":"2022-04-13T08:59:59.273900Z","iopub.status.idle":"2022-04-13T08:59:59.624698Z","shell.execute_reply.started":"2022-04-13T08:59:59.273866Z","shell.execute_reply":"2022-04-13T08:59:59.624013Z"},"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.0001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T08:59:59.625958Z","iopub.execute_input":"2022-04-13T08:59:59.626247Z","iopub.status.idle":"2022-04-13T08:59:59.639356Z","shell.execute_reply.started":"2022-04-13T08:59:59.626188Z","shell.execute_reply":"2022-04-13T08:59:59.638505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh1 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 50, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T08:59:59.642108Z","iopub.execute_input":"2022-04-13T08:59:59.642684Z","iopub.status.idle":"2022-04-13T09:09:07.906080Z","shell.execute_reply.started":"2022-04-13T08:59:59.642648Z","shell.execute_reply":"2022-04-13T09:09:07.905266Z"},"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-13T09:09:07.907743Z","iopub.execute_input":"2022-04-13T09:09:07.907993Z","iopub.status.idle":"2022-04-13T09:09:07.912825Z","shell.execute_reply.started":"2022-04-13T09:09:07.907959Z","shell.execute_reply":"2022-04-13T09:09:07.912141Z"},"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-13T09:09:07.914216Z","iopub.execute_input":"2022-04-13T09:09:07.914681Z","iopub.status.idle":"2022-04-13T09:09:07.925782Z","shell.execute_reply.started":"2022-04-13T09:09:07.914644Z","shell.execute_reply":"2022-04-13T09:09:07.925032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:09:07.927158Z","iopub.execute_input":"2022-04-13T09:09:07.927681Z","iopub.status.idle":"2022-04-13T09:09:08.266764Z","shell.execute_reply.started":"2022-04-13T09:09:07.927644Z","shell.execute_reply":"2022-04-13T09:09:08.266013Z"},"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.00001)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:09:08.267969Z","iopub.execute_input":"2022-04-13T09:09:08.268221Z","iopub.status.idle":"2022-04-13T09:09:08.273470Z","shell.execute_reply.started":"2022-04-13T09:09:08.268189Z","shell.execute_reply":"2022-04-13T09:09:08.272826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 30, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:09:08.274715Z","iopub.execute_input":"2022-04-13T09:09:08.275443Z","iopub.status.idle":"2022-04-13T09:14:33.527525Z","shell.execute_reply.started":"2022-04-13T09:09:08.275404Z","shell.execute_reply":"2022-04-13T09:14:33.526713Z"},"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-13T09:14:33.528873Z","iopub.execute_input":"2022-04-13T09:14:33.529589Z","iopub.status.idle":"2022-04-13T09:14:33.537738Z","shell.execute_reply.started":"2022-04-13T09:14:33.529550Z","shell.execute_reply":"2022-04-13T09:14:33.537084Z"},"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-13T09:14:33.539314Z","iopub.execute_input":"2022-04-13T09:14:33.540250Z","iopub.status.idle":"2022-04-13T09:14:33.937510Z","shell.execute_reply.started":"2022-04-13T09:14:33.540210Z","shell.execute_reply":"2022-04-13T09:14:33.936845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 3 (Fine-Tuning)","metadata":{}},{"cell_type":"code","source":"VGG19_model.trainable = True","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:14:33.938876Z","iopub.execute_input":"2022-04-13T09:14:33.939460Z","iopub.status.idle":"2022-04-13T09:14:33.944997Z","shell.execute_reply.started":"2022-04-13T09:14:33.939384Z","shell.execute_reply":"2022-04-13T09:14:33.944240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.00001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:14:33.946324Z","iopub.execute_input":"2022-04-13T09:14:33.946566Z","iopub.status.idle":"2022-04-13T09:14:33.961100Z","shell.execute_reply.started":"2022-04-13T09:14:33.946529Z","shell.execute_reply":"2022-04-13T09:14:33.960340Z"},"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-13T09:14:33.962597Z","iopub.execute_input":"2022-04-13T09:14:33.963289Z","iopub.status.idle":"2022-04-13T09:19:28.438688Z","shell.execute_reply.started":"2022-04-13T09:14:33.963245Z","shell.execute_reply":"2022-04-13T09:19:28.437137Z"},"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-13T09:19:28.440378Z","iopub.execute_input":"2022-04-13T09:19:28.440628Z","iopub.status.idle":"2022-04-13T09:19:28.806275Z","shell.execute_reply.started":"2022-04-13T09:19:28.440592Z","shell.execute_reply":"2022-04-13T09:19:28.805505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_VGG19_v01.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:19:28.807677Z","iopub.execute_input":"2022-04-13T09:19:28.807926Z","iopub.status.idle":"2022-04-13T09:19:29.406972Z","shell.execute_reply.started":"2022-04-13T09:19:28.807892Z","shell.execute_reply":"2022-04-13T09:19:29.406074Z"},"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-13T09:19:29.415403Z","iopub.execute_input":"2022-04-13T09:19:29.415714Z","iopub.status.idle":"2022-04-13T09:19:41.646541Z","shell.execute_reply.started":"2022-04-13T09:19:29.415682Z","shell.execute_reply":"2022-04-13T09:19:41.645812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T09:19:41.649289Z","iopub.execute_input":"2022-04-13T09:19:41.650348Z","iopub.status.idle":"2022-04-13T09:19:41.656033Z","shell.execute_reply.started":"2022-04-13T09:19:41.650304Z","shell.execute_reply":"2022-04-13T09:19:41.655096Z"},"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-13T09:19:41.657422Z","iopub.execute_input":"2022-04-13T09:19:41.657931Z","iopub.status.idle":"2022-04-13T09:19:42.410859Z","shell.execute_reply.started":"2022-04-13T09:19:41.657891Z","shell.execute_reply":"2022-04-13T09:19:42.410198Z"},"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-13T09:19:42.412210Z","iopub.execute_input":"2022-04-13T09:19:42.412472Z","iopub.status.idle":"2022-04-13T09:19:43.363905Z","shell.execute_reply.started":"2022-04-13T09:19:42.412436Z","shell.execute_reply":"2022-04-13T09:19:43.363167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}