{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":8900,"databundleVersionId":862232,"sourceType":"competition"},{"sourceId":3225959,"sourceType":"datasetVersion","datasetId":1956351},{"sourceId":3394382,"sourceType":"datasetVersion","datasetId":2046290}],"dockerImageVersionId":30163,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2024-05-28T12:40:36.489137Z","iopub.execute_input":"2024-05-28T12:40:36.489432Z","iopub.status.idle":"2024-05-28T12:40:43.886991Z","shell.execute_reply.started":"2024-05-28T12:40:36.489348Z","shell.execute_reply":"2024-05-28T12:40:43.886299Z"},"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":"2024-05-28T12:41:33.149907Z","iopub.execute_input":"2024-05-28T12:41:33.150324Z","iopub.status.idle":"2024-05-28T12:41:33.430886Z","shell.execute_reply.started":"2024-05-28T12:41:33.150274Z","shell.execute_reply":"2024-05-28T12:41:33.429997Z"},"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":"2024-05-28T12:41:35.322568Z","iopub.execute_input":"2024-05-28T12:41:35.322855Z","iopub.status.idle":"2024-05-28T12:41:35.34923Z","shell.execute_reply.started":"2024-05-28T12:41:35.322823Z","shell.execute_reply":"2024-05-28T12:41:35.348452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-28T12:41:37.679441Z","iopub.execute_input":"2024-05-28T12:41:37.680214Z","iopub.status.idle":"2024-05-28T12:41:37.697899Z","shell.execute_reply.started":"2024-05-28T12:41:37.680166Z","shell.execute_reply":"2024-05-28T12:41:37.697078Z"},"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":"2024-05-28T12:41:42.489846Z","iopub.execute_input":"2024-05-28T12:41:42.490585Z","iopub.status.idle":"2024-05-28T12:41:42.502351Z","shell.execute_reply.started":"2024-05-28T12:41:42.490547Z","shell.execute_reply":"2024-05-28T12:41:42.501628Z"},"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":"2024-05-28T12:41:44.989838Z","iopub.execute_input":"2024-05-28T12:41:44.990131Z","iopub.status.idle":"2024-05-28T12:41:45.000361Z","shell.execute_reply.started":"2024-05-28T12:41:44.990098Z","shell.execute_reply":"2024-05-28T12:41:44.999612Z"},"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":"2024-05-28T12:41:47.793814Z","iopub.execute_input":"2024-05-28T12:41:47.794128Z","iopub.status.idle":"2024-05-28T12:41:48.035282Z","shell.execute_reply.started":"2024-05-28T12:41:47.794093Z","shell.execute_reply":"2024-05-28T12:41:48.034514Z"},"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":"2024-05-28T12:41:52.25555Z","iopub.execute_input":"2024-05-28T12:41:52.256159Z","iopub.status.idle":"2024-05-28T12:41:52.270179Z","shell.execute_reply.started":"2024-05-28T12:41:52.256121Z","shell.execute_reply":"2024-05-28T12:41:52.269448Z"},"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":"2024-05-28T12:41:54.648976Z","iopub.execute_input":"2024-05-28T12:41:54.649795Z","iopub.status.idle":"2024-05-28T12:41:55.507826Z","shell.execute_reply.started":"2024-05-28T12:41:54.649759Z","shell.execute_reply":"2024-05-28T12:41:55.507073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(signal.shape)\nprint(sr)\nprint(len(signal) / sr)","metadata":{"execution":{"iopub.status.busy":"2024-05-28T12:41:57.101676Z","iopub.execute_input":"2024-05-28T12:41:57.102412Z","iopub.status.idle":"2024-05-28T12:41:57.107648Z","shell.execute_reply.started":"2024-05-28T12:41:57.10237Z","shell.execute_reply":"2024-05-28T12:41:57.106771Z"},"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":"2024-05-28T12:41:59.590157Z","iopub.execute_input":"2024-05-28T12:41:59.590964Z","iopub.status.idle":"2024-05-28T12:41:59.928502Z","shell.execute_reply.started":"2024-05-28T12:41:59.590931Z","shell.execute_reply":"2024-05-28T12:41:59.927694Z"},"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":"2024-05-28T12:42:02.914668Z","iopub.execute_input":"2024-05-28T12:42:02.915425Z","iopub.status.idle":"2024-05-28T12:42:03.245947Z","shell.execute_reply.started":"2024-05-28T12:42:02.915386Z","shell.execute_reply":"2024-05-28T12:42:03.245241Z"},"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":"2024-05-28T12:42:06.106205Z","iopub.execute_input":"2024-05-28T12:42:06.106803Z","iopub.status.idle":"2024-05-28T12:42:06.133414Z","shell.execute_reply.started":"2024-05-28T12:42:06.106769Z","shell.execute_reply":"2024-05-28T12:42:06.132659Z"},"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":"2024-05-28T12:42:10.78959Z","iopub.execute_input":"2024-05-28T12:42:10.789879Z","iopub.status.idle":"2024-05-28T12:42:11.000788Z","shell.execute_reply.started":"2024-05-28T12:42:10.789847Z","shell.execute_reply":"2024-05-28T12:42:10.999939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(signal.shape)\nprint(sr)\nprint(len(signal) / sr)","metadata":{"execution":{"iopub.status.busy":"2024-05-28T12:42:12.71611Z","iopub.execute_input":"2024-05-28T12:42:12.716394Z","iopub.status.idle":"2024-05-28T12:42:12.72162Z","shell.execute_reply.started":"2024-05-28T12:42:12.716363Z","shell.execute_reply":"2024-05-28T12:42:12.720897Z"},"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":"2024-05-28T12:42:14.509121Z","iopub.execute_input":"2024-05-28T12:42:14.509409Z","iopub.status.idle":"2024-05-28T12:42:14.790591Z","shell.execute_reply.started":"2024-05-28T12:42:14.509377Z","shell.execute_reply":"2024-05-28T12:42:14.789774Z"},"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":"2024-05-28T12:42:18.04685Z","iopub.execute_input":"2024-05-28T12:42:18.047173Z","iopub.status.idle":"2024-05-28T12:42:18.466879Z","shell.execute_reply.started":"2024-05-28T12:42:18.047126Z","shell.execute_reply":"2024-05-28T12:42:18.466092Z"},"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":"2024-05-28T12:42:23.580088Z","iopub.execute_input":"2024-05-28T12:42:23.580426Z","iopub.status.idle":"2024-05-28T12:42:23.596229Z","shell.execute_reply.started":"2024-05-28T12:42:23.580386Z","shell.execute_reply":"2024-05-28T12:42:23.595319Z"},"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":"2024-05-28T12:42:26.336165Z","iopub.execute_input":"2024-05-28T12:42:26.337002Z","iopub.status.idle":"2024-05-28T12:42:30.388606Z","shell.execute_reply.started":"2024-05-28T12:42:26.336961Z","shell.execute_reply":"2024-05-28T12:42:30.387802Z"},"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":"2024-05-28T12:42:39.616215Z","iopub.execute_input":"2024-05-28T12:42:39.616846Z","iopub.status.idle":"2024-05-28T12:42:39.796247Z","shell.execute_reply.started":"2024-05-28T12:42:39.616805Z","shell.execute_reply":"2024-05-28T12:42:39.795051Z"},"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":"2024-05-28T12:42:46.715447Z","iopub.execute_input":"2024-05-28T12:42:46.716186Z","iopub.status.idle":"2024-05-28T12:42:46.738719Z","shell.execute_reply.started":"2024-05-28T12:42:46.716148Z","shell.execute_reply":"2024-05-28T12:42:46.737842Z"},"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":"2024-05-28T12:42:49.489605Z","iopub.execute_input":"2024-05-28T12:42:49.490273Z","iopub.status.idle":"2024-05-28T12:42:49.494906Z","shell.execute_reply.started":"2024-05-28T12:42:49.490234Z","shell.execute_reply":"2024-05-28T12:42:49.494015Z"},"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":"2024-05-28T12:42:51.726062Z","iopub.execute_input":"2024-05-28T12:42:51.726699Z","iopub.status.idle":"2024-05-28T12:42:51.732124Z","shell.execute_reply.started":"2024-05-28T12:42:51.726661Z","shell.execute_reply":"2024-05-28T12:42:51.731319Z"},"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":"2024-05-28T12:42:59.388304Z","iopub.execute_input":"2024-05-28T12:42:59.388612Z","iopub.status.idle":"2024-05-28T12:43:02.892374Z","shell.execute_reply.started":"2024-05-28T12:42:59.38858Z","shell.execute_reply":"2024-05-28T12:43:02.8914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    VGG19_model,\n    \n    Flatten(),\n    \n    Dense(512, activation='relu'),\n    Dropout(0.3),\n    \n    Dense(256, activation='relu'),\n    Dropout(0.3),\n    BatchNormalization(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.3),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.3),\n    BatchNormalization(),\n    \n    Dense(41, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-28T12:44:12.023391Z","iopub.execute_input":"2024-05-28T12:44:12.023683Z","iopub.status.idle":"2024-05-28T12:44:12.167318Z","shell.execute_reply.started":"2024-05-28T12:44:12.02365Z","shell.execute_reply":"2024-05-28T12:44:12.166687Z"},"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":"2024-05-28T12:44:21.802717Z","iopub.execute_input":"2024-05-28T12:44:21.803461Z","iopub.status.idle":"2024-05-28T12:44:21.814615Z","shell.execute_reply.started":"2024-05-28T12:44:21.80342Z","shell.execute_reply":"2024-05-28T12:44:21.813856Z"},"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":"2024-05-28T12:44:26.662669Z","iopub.execute_input":"2024-05-28T12:44:26.663196Z","iopub.status.idle":"2024-05-28T12:55:16.114018Z","shell.execute_reply.started":"2024-05-28T12:44:26.663155Z","shell.execute_reply":"2024-05-28T12:55:16.113204Z"},"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":"2024-05-28T12:57:23.916563Z","iopub.execute_input":"2024-05-28T12:57:23.917265Z","iopub.status.idle":"2024-05-28T12:57:23.922163Z","shell.execute_reply.started":"2024-05-28T12:57:23.917226Z","shell.execute_reply":"2024-05-28T12:57:23.921386Z"},"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":"2024-05-28T12:57:27.468814Z","iopub.execute_input":"2024-05-28T12:57:27.46941Z","iopub.status.idle":"2024-05-28T12:57:27.477577Z","shell.execute_reply.started":"2024-05-28T12:57:27.469372Z","shell.execute_reply":"2024-05-28T12:57:27.476763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2024-05-28T12:57:30.314866Z","iopub.execute_input":"2024-05-28T12:57:30.315625Z","iopub.status.idle":"2024-05-28T12:57:30.754214Z","shell.execute_reply.started":"2024-05-28T12:57:30.315587Z","shell.execute_reply":"2024-05-28T12:57:30.753479Z"},"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":"2024-05-28T12:57:35.290984Z","iopub.execute_input":"2024-05-28T12:57:35.29131Z","iopub.status.idle":"2024-05-28T12:57:35.297048Z","shell.execute_reply.started":"2024-05-28T12:57:35.291262Z","shell.execute_reply":"2024-05-28T12:57:35.296217Z"},"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":"2024-05-28T12:57:37.604336Z","iopub.execute_input":"2024-05-28T12:57:37.605015Z","iopub.status.idle":"2024-05-28T13:04:46.150518Z","shell.execute_reply.started":"2024-05-28T12:57:37.604974Z","shell.execute_reply":"2024-05-28T13:04:46.14975Z"},"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":"2024-05-28T13:05:36.449293Z","iopub.execute_input":"2024-05-28T13:05:36.449594Z","iopub.status.idle":"2024-05-28T13:05:36.458882Z","shell.execute_reply.started":"2024-05-28T13:05:36.449559Z","shell.execute_reply":"2024-05-28T13:05:36.45798Z"},"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":"2024-05-28T13:05:44.314479Z","iopub.execute_input":"2024-05-28T13:05:44.31555Z","iopub.status.idle":"2024-05-28T13:05:44.777767Z","shell.execute_reply.started":"2024-05-28T13:05:44.315488Z","shell.execute_reply":"2024-05-28T13:05:44.777068Z"},"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":"2024-05-28T13:05:49.751946Z","iopub.execute_input":"2024-05-28T13:05:49.752263Z","iopub.status.idle":"2024-05-28T13:05:49.757317Z","shell.execute_reply.started":"2024-05-28T13:05:49.75223Z","shell.execute_reply":"2024-05-28T13:05:49.756329Z"},"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":"2024-05-28T13:05:52.598396Z","iopub.execute_input":"2024-05-28T13:05:52.598684Z","iopub.status.idle":"2024-05-28T13:05:52.611372Z","shell.execute_reply.started":"2024-05-28T13:05:52.598651Z","shell.execute_reply":"2024-05-28T13:05:52.610565Z"},"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":"2024-05-28T13:05:55.357633Z","iopub.execute_input":"2024-05-28T13:05:55.358593Z","iopub.status.idle":"2024-05-28T13:12:15.97311Z","shell.execute_reply.started":"2024-05-28T13:05:55.358529Z","shell.execute_reply":"2024-05-28T13:12:15.972314Z"},"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":"2024-05-28T13:13:19.591685Z","iopub.execute_input":"2024-05-28T13:13:19.59201Z","iopub.status.idle":"2024-05-28T13:13:19.924458Z","shell.execute_reply.started":"2024-05-28T13:13:19.591971Z","shell.execute_reply":"2024-05-28T13:13:19.92323Z"},"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":"2024-05-28T13:13:29.222908Z","iopub.execute_input":"2024-05-28T13:13:29.223203Z","iopub.status.idle":"2024-05-28T13:14:56.648485Z","shell.execute_reply.started":"2024-05-28T13:13:29.223171Z","shell.execute_reply":"2024-05-28T13:14:56.647605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2024-05-28T13:15:47.101344Z","iopub.execute_input":"2024-05-28T13:15:47.101681Z","iopub.status.idle":"2024-05-28T13:15:47.107146Z","shell.execute_reply.started":"2024-05-28T13:15:47.101648Z","shell.execute_reply":"2024-05-28T13:15:47.106316Z"},"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":"2024-05-28T13:15:54.4279Z","iopub.execute_input":"2024-05-28T13:15:54.42822Z","iopub.status.idle":"2024-05-28T13:15:55.284716Z","shell.execute_reply.started":"2024-05-28T13:15:54.428186Z","shell.execute_reply":"2024-05-28T13:15:55.283956Z"},"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":"2024-05-28T13:15:57.842799Z","iopub.execute_input":"2024-05-28T13:15:57.843176Z","iopub.status.idle":"2024-05-28T13:15:58.893344Z","shell.execute_reply.started":"2024-05-28T13:15:57.84314Z","shell.execute_reply":"2024-05-28T13:15:58.892622Z"},"trusted":true},"execution_count":null,"outputs":[]}]}