{"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-13T04:13:12.243488Z","iopub.execute_input":"2022-04-13T04:13:12.244161Z","iopub.status.idle":"2022-04-13T04:13:15.421841Z","shell.execute_reply.started":"2022-04-13T04:13:12.244028Z","shell.execute_reply":"2022-04-13T04:13:15.420580Z"},"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-13T04:13:15.424431Z","iopub.execute_input":"2022-04-13T04:13:15.424742Z","iopub.status.idle":"2022-04-13T04:13:15.438251Z","shell.execute_reply.started":"2022-04-13T04:13:15.424706Z","shell.execute_reply":"2022-04-13T04:13:15.436926Z"},"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-13T04:13:15.440806Z","iopub.execute_input":"2022-04-13T04:13:15.441129Z","iopub.status.idle":"2022-04-13T04:13:15.468085Z","shell.execute_reply.started":"2022-04-13T04:13:15.441072Z","shell.execute_reply":"2022-04-13T04:13:15.467062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:15.471226Z","iopub.execute_input":"2022-04-13T04:13:15.472046Z","iopub.status.idle":"2022-04-13T04:13:15.494502Z","shell.execute_reply.started":"2022-04-13T04:13:15.471987Z","shell.execute_reply":"2022-04-13T04:13:15.493446Z"},"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-13T04:13:15.496715Z","iopub.execute_input":"2022-04-13T04:13:15.497595Z","iopub.status.idle":"2022-04-13T04:13:15.508155Z","shell.execute_reply.started":"2022-04-13T04:13:15.497520Z","shell.execute_reply":"2022-04-13T04:13:15.507113Z"},"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-13T04:13:15.510308Z","iopub.execute_input":"2022-04-13T04:13:15.511390Z","iopub.status.idle":"2022-04-13T04:13:15.525433Z","shell.execute_reply.started":"2022-04-13T04:13:15.511340Z","shell.execute_reply":"2022-04-13T04:13:15.524300Z"},"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-13T04:13:15.527637Z","iopub.execute_input":"2022-04-13T04:13:15.528594Z","iopub.status.idle":"2022-04-13T04:13:15.789402Z","shell.execute_reply.started":"2022-04-13T04:13:15.528391Z","shell.execute_reply":"2022-04-13T04:13:15.788397Z"},"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-13T04:13:15.791584Z","iopub.execute_input":"2022-04-13T04:13:15.792528Z","iopub.status.idle":"2022-04-13T04:13:15.812081Z","shell.execute_reply.started":"2022-04-13T04:13:15.792482Z","shell.execute_reply":"2022-04-13T04:13:15.810961Z"},"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-13T04:13:15.814341Z","iopub.execute_input":"2022-04-13T04:13:15.815247Z","iopub.status.idle":"2022-04-13T04:13:16.762319Z","shell.execute_reply.started":"2022-04-13T04:13:15.815169Z","shell.execute_reply":"2022-04-13T04:13:16.757742Z"},"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-13T04:13:16.768166Z","iopub.execute_input":"2022-04-13T04:13:16.769024Z","iopub.status.idle":"2022-04-13T04:13:16.776976Z","shell.execute_reply.started":"2022-04-13T04:13:16.768977Z","shell.execute_reply":"2022-04-13T04:13:16.775894Z"},"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-13T04:13:16.779097Z","iopub.execute_input":"2022-04-13T04:13:16.780086Z","iopub.status.idle":"2022-04-13T04:13:17.154223Z","shell.execute_reply.started":"2022-04-13T04:13:16.780036Z","shell.execute_reply":"2022-04-13T04:13:17.150993Z"},"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-13T04:13:17.156534Z","iopub.execute_input":"2022-04-13T04:13:17.157406Z","iopub.status.idle":"2022-04-13T04:13:17.679199Z","shell.execute_reply.started":"2022-04-13T04:13:17.157349Z","shell.execute_reply":"2022-04-13T04:13:17.678272Z"},"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-13T04:13:17.681220Z","iopub.execute_input":"2022-04-13T04:13:17.682000Z","iopub.status.idle":"2022-04-13T04:13:17.732851Z","shell.execute_reply.started":"2022-04-13T04:13:17.681954Z","shell.execute_reply":"2022-04-13T04:13:17.731945Z"},"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-13T04:13:17.734651Z","iopub.execute_input":"2022-04-13T04:13:17.735370Z","iopub.status.idle":"2022-04-13T04:13:18.253307Z","shell.execute_reply.started":"2022-04-13T04:13:17.735324Z","shell.execute_reply":"2022-04-13T04:13:18.252256Z"},"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-13T04:13:18.255077Z","iopub.execute_input":"2022-04-13T04:13:18.255650Z","iopub.status.idle":"2022-04-13T04:13:18.263153Z","shell.execute_reply.started":"2022-04-13T04:13:18.255597Z","shell.execute_reply":"2022-04-13T04:13:18.262084Z"},"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-13T04:13:18.264938Z","iopub.execute_input":"2022-04-13T04:13:18.265518Z","iopub.status.idle":"2022-04-13T04:13:18.678489Z","shell.execute_reply.started":"2022-04-13T04:13:18.265469Z","shell.execute_reply":"2022-04-13T04:13:18.677495Z"},"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-13T04:13:18.680748Z","iopub.execute_input":"2022-04-13T04:13:18.681757Z","iopub.status.idle":"2022-04-13T04:13:19.102389Z","shell.execute_reply.started":"2022-04-13T04:13:18.681637Z","shell.execute_reply":"2022-04-13T04:13:19.101449Z"},"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-13T04:13:19.104454Z","iopub.execute_input":"2022-04-13T04:13:19.105216Z","iopub.status.idle":"2022-04-13T04:13:19.125771Z","shell.execute_reply.started":"2022-04-13T04:13:19.105161Z","shell.execute_reply":"2022-04-13T04:13:19.124732Z"},"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-13T04:13:19.127693Z","iopub.execute_input":"2022-04-13T04:13:19.128508Z","iopub.status.idle":"2022-04-13T04:13:22.503444Z","shell.execute_reply.started":"2022-04-13T04:13:19.128462Z","shell.execute_reply":"2022-04-13T04:13:22.502536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Generators","metadata":{}},{"cell_type":"code","source":"SPEC_PATH = '../input/freesound-melpec-128-512-2sec/spectrograms'\nIMG_SIZE = (128,32)\n\nclass DataGenerator(keras.utils.Sequence):\n    \n    def __init__(self, df, batch_size=32, shuffle=True, is_train=True):\n        self.df = df\n        self.n = len(df)\n        self.batch_size = batch_size\n        self.shuffle = shuffle\n        self.is_train = is_train\n        self.on_epoch_end()\n        \n    def on_epoch_end(self):\n        self.indices = np.arange(self.n)\n        if self.shuffle == True:\n            np.random.shuffle(self.indices)   \n    \n    def __len__(self):\n        \n        return math.ceil( self.n / self.batch_size )\n    \n    def __getitem__(self, batch_index):\n        \n        start = batch_index * self.batch_size\n        end = (batch_index + 1) * self.batch_size\n        \n        indices = self.indices[start:end]\n        \n        return self.__data_generation(indices)\n    \n    def __data_generation(self, batch_indices):\n        batch_size = len(batch_indices)\n        \n        X = np.zeros(shape=(batch_size, IMG_SIZE[0], IMG_SIZE[1], 3))\n        y = np.zeros(batch_size)\n        \n        for i, idx in enumerate(batch_indices):\n            FILE = self.df.fname.values[idx]\n            LABEL = self.df.label.values[idx]\n            \n            SET = 'train_spec' if self.is_train else 'test_spec'\n            path = f'{SPEC_PATH}/{SET}/{FILE[:-4]}.npy'\n\n            try:\n                data_array = np.load(path)\n                resized = cv2.resize(data_array, (IMG_SIZE[1], IMG_SIZE[0]))\n                \n                for j in range(3):\n                    X[i,:,:,j] = resized \n                \n            except:\n                print('skipped')\n\n            if self.is_train:\n                y[i] = label_encoder[LABEL]\n\n        if self.is_train:    \n            return X, y\n        return X\n\n    \nGENERATOR_TEST = True\n\nif GENERATOR_TEST:\n    temp_gen = DataGenerator(train, batch_size=8, shuffle=False)\n    X,y = temp_gen.__getitem__(0)\n\n    print(X.shape)\n    print(y)\n    \n    librosa.display.specshow(X[0, :, :, 0])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:22.505118Z","iopub.execute_input":"2022-04-13T04:13:22.505896Z","iopub.status.idle":"2022-04-13T04:13:22.648249Z","shell.execute_reply.started":"2022-04-13T04:13:22.505857Z","shell.execute_reply":"2022-04-13T04:13:22.646869Z"},"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-13T04:13:22.650673Z","iopub.execute_input":"2022-04-13T04:13:22.651068Z","iopub.status.idle":"2022-04-13T04:13:22.713590Z","shell.execute_reply.started":"2022-04-13T04:13:22.651016Z","shell.execute_reply":"2022-04-13T04:13:22.712588Z"},"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-13T04:13:22.715199Z","iopub.execute_input":"2022-04-13T04:13:22.715736Z","iopub.status.idle":"2022-04-13T04:13:22.728229Z","shell.execute_reply.started":"2022-04-13T04:13:22.715686Z","shell.execute_reply":"2022-04-13T04:13:22.727143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TR_STEPS = len(train_loader)\nVA_STEPS = len(valid_loader)\n\nprint(TR_STEPS)\nprint(VA_STEPS)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:22.730012Z","iopub.execute_input":"2022-04-13T04:13:22.730665Z","iopub.status.idle":"2022-04-13T04:13:22.742577Z","shell.execute_reply.started":"2022-04-13T04:13:22.730615Z","shell.execute_reply":"2022-04-13T04:13:22.740954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building CNN","metadata":{}},{"cell_type":"code","source":"RN50_model = tf.keras.applications.ResNet50(input_shape=(128,32,3),include_top=False, weights='imagenet')\nRN50_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:22.744431Z","iopub.execute_input":"2022-04-13T04:13:22.745120Z","iopub.status.idle":"2022-04-13T04:13:25.908594Z","shell.execute_reply.started":"2022-04-13T04:13:22.745067Z","shell.execute_reply":"2022-04-13T04:13:25.907468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    RN50_model,\n    \n    Flatten(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.25),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.25),\n    BatchNormalization(),\n    \n    Dense(32, activation='relu'),\n    Dropout(0.25),\n    BatchNormalization(),\n    \n    Dense(41, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:25.912317Z","iopub.execute_input":"2022-04-13T04:13:25.913405Z","iopub.status.idle":"2022-04-13T04:13:26.508363Z","shell.execute_reply.started":"2022-04-13T04:13:25.913358Z","shell.execute_reply":"2022-04-13T04:13:26.507342Z"},"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.001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:26.510521Z","iopub.execute_input":"2022-04-13T04:13:26.510880Z","iopub.status.idle":"2022-04-13T04:13:26.534863Z","shell.execute_reply.started":"2022-04-13T04:13:26.510834Z","shell.execute_reply":"2022-04-13T04:13:26.533629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh1 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 20, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:13:26.536829Z","iopub.execute_input":"2022-04-13T04:13:26.537612Z","iopub.status.idle":"2022-04-13T04:18:21.372028Z","shell.execute_reply.started":"2022-04-13T04:13:26.537506Z","shell.execute_reply":"2022-04-13T04:18:21.370909Z"},"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-13T04:18:21.379346Z","iopub.execute_input":"2022-04-13T04:18:21.380209Z","iopub.status.idle":"2022-04-13T04:18:21.387333Z","shell.execute_reply.started":"2022-04-13T04:18:21.380135Z","shell.execute_reply":"2022-04-13T04:18:21.386157Z"},"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-13T04:18:21.389459Z","iopub.execute_input":"2022-04-13T04:18:21.390336Z","iopub.status.idle":"2022-04-13T04:18:21.403514Z","shell.execute_reply.started":"2022-04-13T04:18:21.390291Z","shell.execute_reply":"2022-04-13T04:18:21.402489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:18:21.405592Z","iopub.execute_input":"2022-04-13T04:18:21.406413Z","iopub.status.idle":"2022-04-13T04:18:21.915713Z","shell.execute_reply.started":"2022-04-13T04:18:21.406366Z","shell.execute_reply":"2022-04-13T04:18:21.914712Z"},"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.0001)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:18:21.917734Z","iopub.execute_input":"2022-04-13T04:18:21.918489Z","iopub.status.idle":"2022-04-13T04:18:21.925012Z","shell.execute_reply.started":"2022-04-13T04:18:21.918443Z","shell.execute_reply":"2022-04-13T04:18:21.924006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 20, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:18:21.927013Z","iopub.execute_input":"2022-04-13T04:18:21.927831Z","iopub.status.idle":"2022-04-13T04:22:48.978732Z","shell.execute_reply.started":"2022-04-13T04:18:21.927778Z","shell.execute_reply":"2022-04-13T04:22:48.977590Z"},"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-13T04:22:48.980992Z","iopub.execute_input":"2022-04-13T04:22:48.981732Z","iopub.status.idle":"2022-04-13T04:22:48.995838Z","shell.execute_reply.started":"2022-04-13T04:22:48.981679Z","shell.execute_reply":"2022-04-13T04:22:48.994621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:22:48.997855Z","iopub.execute_input":"2022-04-13T04:22:48.999259Z","iopub.status.idle":"2022-04-13T04:22:49.643949Z","shell.execute_reply.started":"2022-04-13T04:22:48.999215Z","shell.execute_reply":"2022-04-13T04:22:49.642606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 3 (Fine-Tuning)","metadata":{}},{"cell_type":"code","source":"RN50_model.trainable = True","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:22:49.646131Z","iopub.execute_input":"2022-04-13T04:22:49.646788Z","iopub.status.idle":"2022-04-13T04:22:49.680051Z","shell.execute_reply.started":"2022-04-13T04:22:49.646728Z","shell.execute_reply":"2022-04-13T04:22:49.678825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"opt = tf.keras.optimizers.Adam(0.0001)\ncnn.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:22:49.682279Z","iopub.execute_input":"2022-04-13T04:22:49.682640Z","iopub.status.idle":"2022-04-13T04:22:49.721647Z","shell.execute_reply.started":"2022-04-13T04:22:49.682599Z","shell.execute_reply":"2022-04-13T04:22:49.720697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh3 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 25, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:22:49.730811Z","iopub.execute_input":"2022-04-13T04:22:49.731710Z","iopub.status.idle":"2022-04-13T04:29:04.090744Z","shell.execute_reply.started":"2022-04-13T04:22:49.731667Z","shell.execute_reply":"2022-04-13T04:29:04.089652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1, h2, h3])\nvis_training(history, start=10)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:29:04.093292Z","iopub.execute_input":"2022-04-13T04:29:04.094405Z","iopub.status.idle":"2022-04-13T04:29:04.554282Z","shell.execute_reply.started":"2022-04-13T04:29:04.094360Z","shell.execute_reply":"2022-04-13T04:29:04.552233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_ResNet50_v01.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:29:04.556302Z","iopub.execute_input":"2022-04-13T04:29:04.557094Z","iopub.status.idle":"2022-04-13T04:29:05.794594Z","shell.execute_reply.started":"2022-04-13T04:29:04.557056Z","shell.execute_reply":"2022-04-13T04:29:05.793627Z"},"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-13T04:29:05.796473Z","iopub.execute_input":"2022-04-13T04:29:05.796861Z","iopub.status.idle":"2022-04-13T04:30:08.925359Z","shell.execute_reply.started":"2022-04-13T04:29:05.796810Z","shell.execute_reply":"2022-04-13T04:30:08.924244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-13T04:30:08.927156Z","iopub.execute_input":"2022-04-13T04:30:08.927789Z","iopub.status.idle":"2022-04-13T04:30:08.935650Z","shell.execute_reply.started":"2022-04-13T04:30:08.927740Z","shell.execute_reply":"2022-04-13T04:30:08.934406Z"},"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-13T04:30:08.937756Z","iopub.execute_input":"2022-04-13T04:30:08.938214Z","iopub.status.idle":"2022-04-13T04:30:10.494705Z","shell.execute_reply.started":"2022-04-13T04:30:08.938164Z","shell.execute_reply":"2022-04-13T04:30:10.493490Z"},"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-13T04:30:10.496948Z","iopub.execute_input":"2022-04-13T04:30:10.497802Z","iopub.status.idle":"2022-04-13T04:30:12.129014Z","shell.execute_reply.started":"2022-04-13T04:30:10.497742Z","shell.execute_reply":"2022-04-13T04:30:12.127600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}