{"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-12T05:54:36.580603Z","iopub.execute_input":"2022-04-12T05:54:36.580944Z","iopub.status.idle":"2022-04-12T05:54:43.383659Z","shell.execute_reply.started":"2022-04-12T05:54:36.580857Z","shell.execute_reply":"2022-04-12T05:54:43.382880Z"},"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-12T05:54:43.386868Z","iopub.execute_input":"2022-04-12T05:54:43.387253Z","iopub.status.idle":"2022-04-12T05:54:43.814040Z","shell.execute_reply.started":"2022-04-12T05:54:43.387214Z","shell.execute_reply":"2022-04-12T05:54:43.813232Z"},"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-12T05:54:43.815414Z","iopub.execute_input":"2022-04-12T05:54:43.815709Z","iopub.status.idle":"2022-04-12T05:54:43.840769Z","shell.execute_reply.started":"2022-04-12T05:54:43.815666Z","shell.execute_reply":"2022-04-12T05:54:43.840007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:54:43.842695Z","iopub.execute_input":"2022-04-12T05:54:43.843005Z","iopub.status.idle":"2022-04-12T05:54:43.860754Z","shell.execute_reply.started":"2022-04-12T05:54:43.842970Z","shell.execute_reply":"2022-04-12T05:54:43.860100Z"},"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-12T05:54:43.862021Z","iopub.execute_input":"2022-04-12T05:54:43.862481Z","iopub.status.idle":"2022-04-12T05:54:43.872995Z","shell.execute_reply.started":"2022-04-12T05:54:43.862445Z","shell.execute_reply":"2022-04-12T05:54:43.872238Z"},"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-12T05:54:43.874499Z","iopub.execute_input":"2022-04-12T05:54:43.875351Z","iopub.status.idle":"2022-04-12T05:54:43.885190Z","shell.execute_reply.started":"2022-04-12T05:54:43.875316Z","shell.execute_reply":"2022-04-12T05:54:43.884095Z"},"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-12T05:54:43.886493Z","iopub.execute_input":"2022-04-12T05:54:43.886852Z","iopub.status.idle":"2022-04-12T05:54:44.089576Z","shell.execute_reply.started":"2022-04-12T05:54:43.886817Z","shell.execute_reply":"2022-04-12T05:54:44.088902Z"},"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-12T05:54:44.090821Z","iopub.execute_input":"2022-04-12T05:54:44.091230Z","iopub.status.idle":"2022-04-12T05:54:44.106107Z","shell.execute_reply.started":"2022-04-12T05:54:44.091194Z","shell.execute_reply":"2022-04-12T05:54:44.105506Z"},"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-12T05:54:44.107007Z","iopub.execute_input":"2022-04-12T05:54:44.107242Z","iopub.status.idle":"2022-04-12T05:54:44.883773Z","shell.execute_reply.started":"2022-04-12T05:54:44.107208Z","shell.execute_reply":"2022-04-12T05:54:44.882254Z"},"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-12T05:54:44.887091Z","iopub.execute_input":"2022-04-12T05:54:44.887284Z","iopub.status.idle":"2022-04-12T05:54:44.891963Z","shell.execute_reply.started":"2022-04-12T05:54:44.887260Z","shell.execute_reply":"2022-04-12T05:54:44.891134Z"},"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-12T05:54:44.893431Z","iopub.execute_input":"2022-04-12T05:54:44.893693Z","iopub.status.idle":"2022-04-12T05:54:45.169885Z","shell.execute_reply.started":"2022-04-12T05:54:44.893661Z","shell.execute_reply":"2022-04-12T05:54:45.169228Z"},"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-12T05:54:45.171062Z","iopub.execute_input":"2022-04-12T05:54:45.171417Z","iopub.status.idle":"2022-04-12T05:54:45.440980Z","shell.execute_reply.started":"2022-04-12T05:54:45.171382Z","shell.execute_reply":"2022-04-12T05:54:45.440370Z"},"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-12T05:54:45.442394Z","iopub.execute_input":"2022-04-12T05:54:45.443095Z","iopub.status.idle":"2022-04-12T05:54:45.490112Z","shell.execute_reply.started":"2022-04-12T05:54:45.443057Z","shell.execute_reply":"2022-04-12T05:54:45.489069Z"},"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-12T05:54:45.491389Z","iopub.execute_input":"2022-04-12T05:54:45.492686Z","iopub.status.idle":"2022-04-12T05:54:45.864758Z","shell.execute_reply.started":"2022-04-12T05:54:45.492642Z","shell.execute_reply":"2022-04-12T05:54:45.863946Z"},"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-12T05:54:45.868458Z","iopub.execute_input":"2022-04-12T05:54:45.870806Z","iopub.status.idle":"2022-04-12T05:54:45.879520Z","shell.execute_reply.started":"2022-04-12T05:54:45.870765Z","shell.execute_reply":"2022-04-12T05:54:45.878681Z"},"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-12T05:54:45.883390Z","iopub.execute_input":"2022-04-12T05:54:45.885696Z","iopub.status.idle":"2022-04-12T05:54:46.212472Z","shell.execute_reply.started":"2022-04-12T05:54:45.885638Z","shell.execute_reply":"2022-04-12T05:54:46.211820Z"},"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-12T05:54:46.213515Z","iopub.execute_input":"2022-04-12T05:54:46.213892Z","iopub.status.idle":"2022-04-12T05:54:46.525092Z","shell.execute_reply.started":"2022-04-12T05:54:46.213853Z","shell.execute_reply":"2022-04-12T05:54:46.524386Z"},"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-12T05:54:46.526448Z","iopub.execute_input":"2022-04-12T05:54:46.526901Z","iopub.status.idle":"2022-04-12T05:54:46.540438Z","shell.execute_reply.started":"2022-04-12T05:54:46.526865Z","shell.execute_reply":"2022-04-12T05:54:46.539700Z"},"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-12T05:54:46.541853Z","iopub.execute_input":"2022-04-12T05:54:46.542119Z","iopub.status.idle":"2022-04-12T05:54:49.273127Z","shell.execute_reply.started":"2022-04-12T05:54:46.542083Z","shell.execute_reply":"2022-04-12T05:54:49.272466Z"},"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                X[i,:,:,0] = resized                \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-12T05:54:49.274161Z","iopub.execute_input":"2022-04-12T05:54:49.274564Z","iopub.status.idle":"2022-04-12T05:54:49.446169Z","shell.execute_reply.started":"2022-04-12T05:54:49.274504Z","shell.execute_reply":"2022-04-12T05:54:49.445338Z"},"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-12T05:54:49.447672Z","iopub.execute_input":"2022-04-12T05:54:49.447901Z","iopub.status.idle":"2022-04-12T05:54:49.480920Z","shell.execute_reply.started":"2022-04-12T05:54:49.447869Z","shell.execute_reply":"2022-04-12T05:54:49.480232Z"},"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-12T05:54:49.482270Z","iopub.execute_input":"2022-04-12T05:54:49.482728Z","iopub.status.idle":"2022-04-12T05:54:49.488007Z","shell.execute_reply.started":"2022-04-12T05:54:49.482692Z","shell.execute_reply":"2022-04-12T05:54:49.487049Z"},"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.4))\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.4))\ncnn.add(BatchNormalization())\n\n\ncnn.add(Flatten())\n\ncnn.add(Dense(128, activation='relu'))\ncnn.add(Dropout(0.4))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(64, activation='relu'))\ncnn.add(Dropout(0.4))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(41, activation='softmax'))\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:54:49.489724Z","iopub.execute_input":"2022-04-12T05:54:49.490237Z","iopub.status.idle":"2022-04-12T05:54:52.164904Z","shell.execute_reply.started":"2022-04-12T05:54:49.490200Z","shell.execute_reply":"2022-04-12T05:54:52.164164Z"},"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-12T05:54:52.166391Z","iopub.execute_input":"2022-04-12T05:54:52.166658Z","iopub.status.idle":"2022-04-12T05:59:56.592461Z","shell.execute_reply.started":"2022-04-12T05:54:52.166624Z","shell.execute_reply":"2022-04-12T05:59:56.591615Z"},"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-12T05:59:56.594062Z","iopub.execute_input":"2022-04-12T05:59:56.596673Z","iopub.status.idle":"2022-04-12T05:59:56.602635Z","shell.execute_reply.started":"2022-04-12T05:59:56.596640Z","shell.execute_reply":"2022-04-12T05:59:56.601747Z"},"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-12T05:59:56.604693Z","iopub.execute_input":"2022-04-12T05:59:56.605253Z","iopub.status.idle":"2022-04-12T05:59:56.615607Z","shell.execute_reply.started":"2022-04-12T05:59:56.605214Z","shell.execute_reply":"2022-04-12T05:59:56.614576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:59:56.617064Z","iopub.execute_input":"2022-04-12T05:59:56.617886Z","iopub.status.idle":"2022-04-12T05:59:56.981362Z","shell.execute_reply.started":"2022-04-12T05:59:56.617846Z","shell.execute_reply":"2022-04-12T05:59:56.980693Z"},"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-12T05:59:56.985770Z","iopub.execute_input":"2022-04-12T05:59:56.986003Z","iopub.status.idle":"2022-04-12T05:59:56.990993Z","shell.execute_reply.started":"2022-04-12T05:59:56.985963Z","shell.execute_reply":"2022-04-12T05:59:56.990141Z"},"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-12T05:59:56.992490Z","iopub.execute_input":"2022-04-12T05:59:56.992751Z","iopub.status.idle":"2022-04-12T06:03:55.501885Z","shell.execute_reply.started":"2022-04-12T05:59:56.992719Z","shell.execute_reply":"2022-04-12T06:03:55.501139Z"},"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-12T06:03:55.503504Z","iopub.execute_input":"2022-04-12T06:03:55.504072Z","iopub.status.idle":"2022-04-12T06:03:55.514233Z","shell.execute_reply.started":"2022-04-12T06:03:55.504035Z","shell.execute_reply":"2022-04-12T06:03:55.512953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h2])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-12T06:03:55.517370Z","iopub.execute_input":"2022-04-12T06:03:55.518240Z","iopub.status.idle":"2022-04-12T06:03:56.129252Z","shell.execute_reply.started":"2022-04-12T06:03:55.518202Z","shell.execute_reply":"2022-04-12T06:03:56.128594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_v03.h1')","metadata":{"execution":{"iopub.status.busy":"2022-04-12T06:03:56.132954Z","iopub.execute_input":"2022-04-12T06:03:56.134791Z","iopub.status.idle":"2022-04-12T06:03:59.165948Z","shell.execute_reply.started":"2022-04-12T06:03:56.134752Z","shell.execute_reply":"2022-04-12T06:03:59.165214Z"},"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-12T06:03:59.167716Z","iopub.execute_input":"2022-04-12T06:03:59.167944Z","iopub.status.idle":"2022-04-12T06:05:05.528659Z","shell.execute_reply.started":"2022-04-12T06:03:59.167908Z","shell.execute_reply":"2022-04-12T06:05:05.527890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-12T06:05:05.529973Z","iopub.execute_input":"2022-04-12T06:05:05.530229Z","iopub.status.idle":"2022-04-12T06:05:05.537376Z","shell.execute_reply.started":"2022-04-12T06:05:05.530192Z","shell.execute_reply":"2022-04-12T06:05:05.536503Z"},"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-12T06:05:05.538845Z","iopub.execute_input":"2022-04-12T06:05:05.539089Z","iopub.status.idle":"2022-04-12T06:05:06.287043Z","shell.execute_reply.started":"2022-04-12T06:05:05.539056Z","shell.execute_reply":"2022-04-12T06:05:06.286372Z"},"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-12T06:05:06.288291Z","iopub.execute_input":"2022-04-12T06:05:06.288539Z","iopub.status.idle":"2022-04-12T06:05:07.267295Z","shell.execute_reply.started":"2022-04-12T06:05:06.288511Z","shell.execute_reply":"2022-04-12T06:05:07.266507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}