{"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-13T05:59:35.429383Z","iopub.execute_input":"2022-04-13T05:59:35.430898Z","iopub.status.idle":"2022-04-13T05:59:37.760417Z","shell.execute_reply.started":"2022-04-13T05:59:35.430809Z","shell.execute_reply":"2022-04-13T05:59:37.759581Z"},"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-13T05:59:37.762323Z","iopub.execute_input":"2022-04-13T05:59:37.762527Z","iopub.status.idle":"2022-04-13T05:59:37.772564Z","shell.execute_reply.started":"2022-04-13T05:59:37.762503Z","shell.execute_reply":"2022-04-13T05:59:37.771864Z"},"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-13T05:59:37.774503Z","iopub.execute_input":"2022-04-13T05:59:37.775422Z","iopub.status.idle":"2022-04-13T05:59:37.802305Z","shell.execute_reply.started":"2022-04-13T05:59:37.775103Z","shell.execute_reply":"2022-04-13T05:59:37.801639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T05:59:37.805357Z","iopub.execute_input":"2022-04-13T05:59:37.806415Z","iopub.status.idle":"2022-04-13T05:59:37.825002Z","shell.execute_reply.started":"2022-04-13T05:59:37.806379Z","shell.execute_reply":"2022-04-13T05:59:37.824264Z"},"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-13T05:59:37.826938Z","iopub.execute_input":"2022-04-13T05:59:37.827971Z","iopub.status.idle":"2022-04-13T05:59:37.838025Z","shell.execute_reply.started":"2022-04-13T05:59:37.827935Z","shell.execute_reply":"2022-04-13T05:59:37.837083Z"},"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-13T05:59:37.840332Z","iopub.execute_input":"2022-04-13T05:59:37.841414Z","iopub.status.idle":"2022-04-13T05:59:37.853226Z","shell.execute_reply.started":"2022-04-13T05:59:37.841379Z","shell.execute_reply":"2022-04-13T05:59:37.852246Z"},"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-13T05:59:37.855107Z","iopub.execute_input":"2022-04-13T05:59:37.856057Z","iopub.status.idle":"2022-04-13T05:59:38.063735Z","shell.execute_reply.started":"2022-04-13T05:59:37.856022Z","shell.execute_reply":"2022-04-13T05:59:38.063016Z"},"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-13T05:59:38.065753Z","iopub.execute_input":"2022-04-13T05:59:38.066721Z","iopub.status.idle":"2022-04-13T05:59:38.083824Z","shell.execute_reply.started":"2022-04-13T05:59:38.066684Z","shell.execute_reply":"2022-04-13T05:59:38.083143Z"},"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-13T05:59:38.084723Z","iopub.execute_input":"2022-04-13T05:59:38.084989Z","iopub.status.idle":"2022-04-13T05:59:38.960775Z","shell.execute_reply.started":"2022-04-13T05:59:38.084956Z","shell.execute_reply":"2022-04-13T05:59:38.959889Z"},"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-13T05:59:38.962964Z","iopub.execute_input":"2022-04-13T05:59:38.963235Z","iopub.status.idle":"2022-04-13T05:59:38.970056Z","shell.execute_reply.started":"2022-04-13T05:59:38.963197Z","shell.execute_reply":"2022-04-13T05:59:38.969279Z"},"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-13T05:59:38.971755Z","iopub.execute_input":"2022-04-13T05:59:38.972960Z","iopub.status.idle":"2022-04-13T05:59:39.322137Z","shell.execute_reply.started":"2022-04-13T05:59:38.972922Z","shell.execute_reply":"2022-04-13T05:59:39.321477Z"},"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-13T05:59:39.323811Z","iopub.execute_input":"2022-04-13T05:59:39.324208Z","iopub.status.idle":"2022-04-13T05:59:39.642195Z","shell.execute_reply.started":"2022-04-13T05:59:39.324169Z","shell.execute_reply":"2022-04-13T05:59:39.641448Z"},"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-13T05:59:39.646199Z","iopub.execute_input":"2022-04-13T05:59:39.647421Z","iopub.status.idle":"2022-04-13T05:59:39.675022Z","shell.execute_reply.started":"2022-04-13T05:59:39.647384Z","shell.execute_reply":"2022-04-13T05:59:39.674273Z"},"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-13T05:59:39.676759Z","iopub.execute_input":"2022-04-13T05:59:39.677861Z","iopub.status.idle":"2022-04-13T05:59:40.068019Z","shell.execute_reply.started":"2022-04-13T05:59:39.677823Z","shell.execute_reply":"2022-04-13T05:59:40.066713Z"},"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-13T05:59:40.069943Z","iopub.execute_input":"2022-04-13T05:59:40.071163Z","iopub.status.idle":"2022-04-13T05:59:40.077632Z","shell.execute_reply.started":"2022-04-13T05:59:40.071094Z","shell.execute_reply":"2022-04-13T05:59:40.076776Z"},"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-13T05:59:40.079695Z","iopub.execute_input":"2022-04-13T05:59:40.080956Z","iopub.status.idle":"2022-04-13T05:59:40.726251Z","shell.execute_reply.started":"2022-04-13T05:59:40.080915Z","shell.execute_reply":"2022-04-13T05:59:40.725618Z"},"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-13T05:59:40.728253Z","iopub.execute_input":"2022-04-13T05:59:40.729939Z","iopub.status.idle":"2022-04-13T05:59:41.201819Z","shell.execute_reply.started":"2022-04-13T05:59:40.729897Z","shell.execute_reply":"2022-04-13T05:59:41.200623Z"},"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-13T05:59:41.204261Z","iopub.execute_input":"2022-04-13T05:59:41.206209Z","iopub.status.idle":"2022-04-13T05:59:41.228262Z","shell.execute_reply.started":"2022-04-13T05:59:41.206128Z","shell.execute_reply":"2022-04-13T05:59:41.227262Z"},"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-13T05:59:41.230377Z","iopub.execute_input":"2022-04-13T05:59:41.231271Z","iopub.status.idle":"2022-04-13T05:59:44.335525Z","shell.execute_reply.started":"2022-04-13T05:59:41.231226Z","shell.execute_reply":"2022-04-13T05:59:44.334657Z"},"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], 1))\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,:,:,0] = 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-13T05:59:44.343409Z","iopub.execute_input":"2022-04-13T05:59:44.343857Z","iopub.status.idle":"2022-04-13T05:59:44.447712Z","shell.execute_reply.started":"2022-04-13T05:59:44.343816Z","shell.execute_reply":"2022-04-13T05:59:44.446821Z"},"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-13T05:59:44.449879Z","iopub.execute_input":"2022-04-13T05:59:44.450155Z","iopub.status.idle":"2022-04-13T05:59:44.499978Z","shell.execute_reply.started":"2022-04-13T05:59:44.450119Z","shell.execute_reply":"2022-04-13T05:59:44.499089Z"},"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-13T05:59:44.501380Z","iopub.execute_input":"2022-04-13T05:59:44.503095Z","iopub.status.idle":"2022-04-13T05:59:44.510374Z","shell.execute_reply.started":"2022-04-13T05:59:44.503061Z","shell.execute_reply":"2022-04-13T05:59:44.509546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building CNN","metadata":{}},{"cell_type":"code","source":"np.random.seed(1)\n\ncnn = Sequential()\n\ncnn.add(Conv2D(32, (3,3), activation = 'relu', padding = 'same', input_shape=(128,32,1)))\ncnn.add(Conv2D(32, (3,3), activation = 'relu', padding = 'same'))\ncnn.add(MaxPooling2D(2,2))\ncnn.add(Dropout(0.50))\ncnn.add(BatchNormalization())\n\ncnn.add(Conv2D(64, (3,3), activation = 'relu', padding = 'same'))\ncnn.add(Conv2D(64, (3,3), activation = 'relu', padding = 'same'))\ncnn.add(MaxPooling2D(2,2))\ncnn.add(Dropout(0.50))\ncnn.add(BatchNormalization())\n\n\ncnn.add(Flatten())\n\ncnn.add(Dense(128, activation='relu'))\ncnn.add(Dropout(0.5))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(64, activation='relu'))\ncnn.add(Dropout(0.50))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(41, activation='softmax'))\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T05:59:44.512779Z","iopub.execute_input":"2022-04-13T05:59:44.513541Z","iopub.status.idle":"2022-04-13T05:59:45.797347Z","shell.execute_reply.started":"2022-04-13T05:59:44.513500Z","shell.execute_reply":"2022-04-13T05:59:45.796644Z"},"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":"%%time\n\nopt = tf.keras.optimizers.Adam(0.001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n\nh1 = cnn.fit(train_loader, epochs = 25, validation_data = valid_loader, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T05:59:45.800297Z","iopub.execute_input":"2022-04-13T05:59:45.800550Z","iopub.status.idle":"2022-04-13T06:06:26.782574Z","shell.execute_reply.started":"2022-04-13T05:59:45.800514Z","shell.execute_reply":"2022-04-13T06:06:26.781794Z"},"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:06:26.784283Z","iopub.execute_input":"2022-04-13T06:06:26.784734Z","iopub.status.idle":"2022-04-13T06:06:26.790238Z","shell.execute_reply.started":"2022-04-13T06:06:26.784695Z","shell.execute_reply":"2022-04-13T06:06:26.789545Z"},"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:06:26.791845Z","iopub.execute_input":"2022-04-13T06:06:26.792414Z","iopub.status.idle":"2022-04-13T06:06:26.803357Z","shell.execute_reply.started":"2022-04-13T06:06:26.792372Z","shell.execute_reply":"2022-04-13T06:06:26.802326Z"},"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:06:26.804866Z","iopub.execute_input":"2022-04-13T06:06:26.805349Z","iopub.status.idle":"2022-04-13T06:06:27.395961Z","shell.execute_reply.started":"2022-04-13T06:06:26.805312Z","shell.execute_reply":"2022-04-13T06:06:27.395265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 2","metadata":{}},{"cell_type":"code","source":"tf.keras.backend.set_value(cnn.optimizer.learning_rate, 0.0001)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:06:27.397216Z","iopub.execute_input":"2022-04-13T06:06:27.397635Z","iopub.status.idle":"2022-04-13T06:06:27.402995Z","shell.execute_reply.started":"2022-04-13T06:06:27.397582Z","shell.execute_reply":"2022-04-13T06:06:27.402329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nh2 = cnn.fit(train_loader, epochs = 25, validation_data = valid_loader, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:06:27.404396Z","iopub.execute_input":"2022-04-13T06:06:27.404828Z","iopub.status.idle":"2022-04-13T06:12:32.589091Z","shell.execute_reply.started":"2022-04-13T06:06:27.404791Z","shell.execute_reply":"2022-04-13T06:12:32.584680Z"},"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:12:32.591268Z","iopub.execute_input":"2022-04-13T06:12:32.591537Z","iopub.status.idle":"2022-04-13T06:12:32.602288Z","shell.execute_reply.started":"2022-04-13T06:12:32.591488Z","shell.execute_reply":"2022-04-13T06:12:32.601633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h2])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:12:32.603863Z","iopub.execute_input":"2022-04-13T06:12:32.605025Z","iopub.status.idle":"2022-04-13T06:12:33.020838Z","shell.execute_reply.started":"2022-04-13T06:12:32.604801Z","shell.execute_reply":"2022-04-13T06:12:33.018670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_v01.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:12:33.022550Z","iopub.execute_input":"2022-04-13T06:12:33.023236Z","iopub.status.idle":"2022-04-13T06:12:33.164540Z","shell.execute_reply.started":"2022-04-13T06:12:33.023195Z","shell.execute_reply":"2022-04-13T06:12:33.163797Z"},"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:12:33.166006Z","iopub.execute_input":"2022-04-13T06:12:33.166402Z","iopub.status.idle":"2022-04-13T06:12:42.934118Z","shell.execute_reply.started":"2022-04-13T06:12:33.166363Z","shell.execute_reply":"2022-04-13T06:12:42.931514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T06:12:42.936079Z","iopub.execute_input":"2022-04-13T06:12:42.936803Z","iopub.status.idle":"2022-04-13T06:12:42.945092Z","shell.execute_reply.started":"2022-04-13T06:12:42.936760Z","shell.execute_reply":"2022-04-13T06:12:42.944269Z"},"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:12:42.947223Z","iopub.execute_input":"2022-04-13T06:12:42.948480Z","iopub.status.idle":"2022-04-13T06:12:43.733131Z","shell.execute_reply.started":"2022-04-13T06:12:42.948441Z","shell.execute_reply":"2022-04-13T06:12:43.732449Z"},"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:12:43.735175Z","iopub.execute_input":"2022-04-13T06:12:43.736144Z","iopub.status.idle":"2022-04-13T06:12:44.649025Z","shell.execute_reply.started":"2022-04-13T06:12:43.736107Z","shell.execute_reply":"2022-04-13T06:12:44.647560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}