{"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:11:25.328191Z","iopub.execute_input":"2022-04-12T05:11:25.328968Z","iopub.status.idle":"2022-04-12T05:11:32.089681Z","shell.execute_reply.started":"2022-04-12T05:11:25.328869Z","shell.execute_reply":"2022-04-12T05:11:32.088822Z"},"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:11:32.091190Z","iopub.execute_input":"2022-04-12T05:11:32.091437Z","iopub.status.idle":"2022-04-12T05:11:32.321742Z","shell.execute_reply.started":"2022-04-12T05:11:32.091405Z","shell.execute_reply":"2022-04-12T05:11:32.320936Z"},"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:11:32.323302Z","iopub.execute_input":"2022-04-12T05:11:32.323832Z","iopub.status.idle":"2022-04-12T05:11:32.346493Z","shell.execute_reply.started":"2022-04-12T05:11:32.323778Z","shell.execute_reply":"2022-04-12T05:11:32.345701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:11:32.348559Z","iopub.execute_input":"2022-04-12T05:11:32.348796Z","iopub.status.idle":"2022-04-12T05:11:32.366165Z","shell.execute_reply.started":"2022-04-12T05:11:32.348765Z","shell.execute_reply":"2022-04-12T05:11:32.365516Z"},"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:11:32.367901Z","iopub.execute_input":"2022-04-12T05:11:32.368586Z","iopub.status.idle":"2022-04-12T05:11:32.378831Z","shell.execute_reply.started":"2022-04-12T05:11:32.368543Z","shell.execute_reply":"2022-04-12T05:11:32.377835Z"},"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:11:32.380437Z","iopub.execute_input":"2022-04-12T05:11:32.380836Z","iopub.status.idle":"2022-04-12T05:11:32.390136Z","shell.execute_reply.started":"2022-04-12T05:11:32.380803Z","shell.execute_reply":"2022-04-12T05:11:32.389373Z"},"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:11:32.391663Z","iopub.execute_input":"2022-04-12T05:11:32.392570Z","iopub.status.idle":"2022-04-12T05:11:32.598757Z","shell.execute_reply.started":"2022-04-12T05:11:32.392536Z","shell.execute_reply":"2022-04-12T05:11:32.598077Z"},"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:11:32.599870Z","iopub.execute_input":"2022-04-12T05:11:32.600101Z","iopub.status.idle":"2022-04-12T05:11:32.615957Z","shell.execute_reply.started":"2022-04-12T05:11:32.600067Z","shell.execute_reply":"2022-04-12T05:11:32.615362Z"},"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:11:32.616850Z","iopub.execute_input":"2022-04-12T05:11:32.617068Z","iopub.status.idle":"2022-04-12T05:11:33.436352Z","shell.execute_reply.started":"2022-04-12T05:11:32.617037Z","shell.execute_reply":"2022-04-12T05:11:33.435528Z"},"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:11:33.440424Z","iopub.execute_input":"2022-04-12T05:11:33.441002Z","iopub.status.idle":"2022-04-12T05:11:33.446541Z","shell.execute_reply.started":"2022-04-12T05:11:33.440968Z","shell.execute_reply":"2022-04-12T05:11:33.445596Z"},"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:11:33.447925Z","iopub.execute_input":"2022-04-12T05:11:33.448392Z","iopub.status.idle":"2022-04-12T05:11:33.773903Z","shell.execute_reply.started":"2022-04-12T05:11:33.448355Z","shell.execute_reply":"2022-04-12T05:11:33.772948Z"},"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:11:33.775274Z","iopub.execute_input":"2022-04-12T05:11:33.775695Z","iopub.status.idle":"2022-04-12T05:11:34.107073Z","shell.execute_reply.started":"2022-04-12T05:11:33.775655Z","shell.execute_reply":"2022-04-12T05:11:34.106194Z"},"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:11:34.108448Z","iopub.execute_input":"2022-04-12T05:11:34.108799Z","iopub.status.idle":"2022-04-12T05:11:34.144741Z","shell.execute_reply.started":"2022-04-12T05:11:34.108759Z","shell.execute_reply":"2022-04-12T05:11:34.143899Z"},"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:11:34.146043Z","iopub.execute_input":"2022-04-12T05:11:34.146275Z","iopub.status.idle":"2022-04-12T05:11:34.385887Z","shell.execute_reply.started":"2022-04-12T05:11:34.146233Z","shell.execute_reply":"2022-04-12T05:11:34.384710Z"},"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:11:34.387208Z","iopub.execute_input":"2022-04-12T05:11:34.387648Z","iopub.status.idle":"2022-04-12T05:11:34.393495Z","shell.execute_reply.started":"2022-04-12T05:11:34.387614Z","shell.execute_reply":"2022-04-12T05:11:34.392687Z"},"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:11:34.395188Z","iopub.execute_input":"2022-04-12T05:11:34.395900Z","iopub.status.idle":"2022-04-12T05:11:34.754069Z","shell.execute_reply.started":"2022-04-12T05:11:34.395851Z","shell.execute_reply":"2022-04-12T05:11:34.753213Z"},"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:11:34.755662Z","iopub.execute_input":"2022-04-12T05:11:34.755942Z","iopub.status.idle":"2022-04-12T05:11:35.121047Z","shell.execute_reply.started":"2022-04-12T05:11:34.755904Z","shell.execute_reply":"2022-04-12T05:11:35.120145Z"},"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:11:35.122793Z","iopub.execute_input":"2022-04-12T05:11:35.123456Z","iopub.status.idle":"2022-04-12T05:11:35.141189Z","shell.execute_reply.started":"2022-04-12T05:11:35.123412Z","shell.execute_reply":"2022-04-12T05:11:35.140292Z"},"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:11:35.143014Z","iopub.execute_input":"2022-04-12T05:11:35.143488Z","iopub.status.idle":"2022-04-12T05:11:38.142681Z","shell.execute_reply.started":"2022-04-12T05:11:35.143442Z","shell.execute_reply":"2022-04-12T05:11:38.142062Z"},"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:11:38.144320Z","iopub.execute_input":"2022-04-12T05:11:38.145002Z","iopub.status.idle":"2022-04-12T05:11:38.294125Z","shell.execute_reply.started":"2022-04-12T05:11:38.144937Z","shell.execute_reply":"2022-04-12T05:11:38.293300Z"},"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:11:38.298886Z","iopub.execute_input":"2022-04-12T05:11:38.299206Z","iopub.status.idle":"2022-04-12T05:11:38.337953Z","shell.execute_reply.started":"2022-04-12T05:11:38.299166Z","shell.execute_reply":"2022-04-12T05:11:38.337095Z"},"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:11:38.342470Z","iopub.execute_input":"2022-04-12T05:11:38.342779Z","iopub.status.idle":"2022-04-12T05:11:38.352207Z","shell.execute_reply.started":"2022-04-12T05:11:38.342729Z","shell.execute_reply":"2022-04-12T05:11:38.351112Z"},"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.3))\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.3))\ncnn.add(BatchNormalization())\n\n\ncnn.add(Flatten())\n\ncnn.add(Dense(128, activation='relu'))\ncnn.add(Dropout(0.3))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(64, activation='relu'))\ncnn.add(Dropout(0.3))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(41, activation='softmax'))\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:11:38.357798Z","iopub.execute_input":"2022-04-12T05:11:38.358101Z","iopub.status.idle":"2022-04-12T05:11:40.787379Z","shell.execute_reply.started":"2022-04-12T05:11:38.358065Z","shell.execute_reply":"2022-04-12T05:11:40.786638Z"},"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:11:40.788632Z","iopub.execute_input":"2022-04-12T05:11:40.788861Z","iopub.status.idle":"2022-04-12T05:16:09.191687Z","shell.execute_reply.started":"2022-04-12T05:11:40.788828Z","shell.execute_reply":"2022-04-12T05:16:09.190912Z"},"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:16:09.193216Z","iopub.execute_input":"2022-04-12T05:16:09.193563Z","iopub.status.idle":"2022-04-12T05:16:09.198983Z","shell.execute_reply.started":"2022-04-12T05:16:09.193524Z","shell.execute_reply":"2022-04-12T05:16:09.198036Z"},"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:16:09.200407Z","iopub.execute_input":"2022-04-12T05:16:09.200949Z","iopub.status.idle":"2022-04-12T05:16:09.210867Z","shell.execute_reply.started":"2022-04-12T05:16:09.200910Z","shell.execute_reply":"2022-04-12T05:16:09.209952Z"},"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:16:09.212318Z","iopub.execute_input":"2022-04-12T05:16:09.212807Z","iopub.status.idle":"2022-04-12T05:16:09.612758Z","shell.execute_reply.started":"2022-04-12T05:16:09.212769Z","shell.execute_reply":"2022-04-12T05:16:09.612105Z"},"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:16:09.616549Z","iopub.execute_input":"2022-04-12T05:16:09.616879Z","iopub.status.idle":"2022-04-12T05:16:09.621596Z","shell.execute_reply.started":"2022-04-12T05:16:09.616850Z","shell.execute_reply":"2022-04-12T05:16:09.620934Z"},"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:16:09.622831Z","iopub.execute_input":"2022-04-12T05:16:09.623669Z","iopub.status.idle":"2022-04-12T05:20:07.382363Z","shell.execute_reply.started":"2022-04-12T05:16:09.623609Z","shell.execute_reply":"2022-04-12T05:20:07.381545Z"},"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:20:07.384141Z","iopub.execute_input":"2022-04-12T05:20:07.384439Z","iopub.status.idle":"2022-04-12T05:20:07.394729Z","shell.execute_reply.started":"2022-04-12T05:20:07.384401Z","shell.execute_reply":"2022-04-12T05:20:07.393888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h2])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:20:07.396303Z","iopub.execute_input":"2022-04-12T05:20:07.396832Z","iopub.status.idle":"2022-04-12T05:20:07.782831Z","shell.execute_reply.started":"2022-04-12T05:20:07.396790Z","shell.execute_reply":"2022-04-12T05:20:07.782103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_v02.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:20:07.784186Z","iopub.execute_input":"2022-04-12T05:20:07.784459Z","iopub.status.idle":"2022-04-12T05:20:07.888601Z","shell.execute_reply.started":"2022-04-12T05:20:07.784422Z","shell.execute_reply":"2022-04-12T05:20:07.887855Z"},"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-12T05:20:07.889784Z","iopub.execute_input":"2022-04-12T05:20:07.890045Z","iopub.status.idle":"2022-04-12T05:20:41.317483Z","shell.execute_reply.started":"2022-04-12T05:20:07.890004Z","shell.execute_reply":"2022-04-12T05:20:41.316727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-12T05:20:41.318962Z","iopub.execute_input":"2022-04-12T05:20:41.319465Z","iopub.status.idle":"2022-04-12T05:20:41.326322Z","shell.execute_reply.started":"2022-04-12T05:20:41.319425Z","shell.execute_reply":"2022-04-12T05:20:41.325343Z"},"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-12T05:20:41.328581Z","iopub.execute_input":"2022-04-12T05:20:41.329443Z","iopub.status.idle":"2022-04-12T05:20:42.119884Z","shell.execute_reply.started":"2022-04-12T05:20:41.329400Z","shell.execute_reply":"2022-04-12T05:20:42.119140Z"},"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-12T05:20:42.121184Z","iopub.execute_input":"2022-04-12T05:20:42.121624Z","iopub.status.idle":"2022-04-12T05:20:43.083866Z","shell.execute_reply.started":"2022-04-12T05:20:42.121584Z","shell.execute_reply":"2022-04-12T05:20:43.083118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}