{"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":"!pip install -U efficientnet -qq","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:24:50.284808Z","iopub.execute_input":"2022-04-14T19:24:50.285170Z","iopub.status.idle":"2022-04-14T19:24:58.454965Z","shell.execute_reply.started":"2022-04-14T19:24:50.285089Z","shell.execute_reply":"2022-04-14T19:24:58.453938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nimport efficientnet.tfkeras as efn\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:24:58.460436Z","iopub.execute_input":"2022-04-14T19:24:58.461103Z","iopub.status.idle":"2022-04-14T19:25:00.887932Z","shell.execute_reply.started":"2022-04-14T19:24:58.461062Z","shell.execute_reply":"2022-04-14T19:25:00.887052Z"},"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-14T19:25:00.889343Z","iopub.execute_input":"2022-04-14T19:25:00.889659Z","iopub.status.idle":"2022-04-14T19:25:00.902352Z","shell.execute_reply.started":"2022-04-14T19:25:00.889622Z","shell.execute_reply":"2022-04-14T19:25:00.901399Z"},"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-14T19:25:00.905647Z","iopub.execute_input":"2022-04-14T19:25:00.906133Z","iopub.status.idle":"2022-04-14T19:25:00.925046Z","shell.execute_reply.started":"2022-04-14T19:25:00.906093Z","shell.execute_reply":"2022-04-14T19:25:00.924154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:25:00.927672Z","iopub.execute_input":"2022-04-14T19:25:00.928075Z","iopub.status.idle":"2022-04-14T19:25:00.945649Z","shell.execute_reply.started":"2022-04-14T19:25:00.928040Z","shell.execute_reply":"2022-04-14T19:25:00.944808Z"},"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-14T19:25:00.948226Z","iopub.execute_input":"2022-04-14T19:25:00.948790Z","iopub.status.idle":"2022-04-14T19:25:00.957160Z","shell.execute_reply.started":"2022-04-14T19:25:00.948684Z","shell.execute_reply":"2022-04-14T19:25:00.956107Z"},"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-14T19:25:00.958727Z","iopub.execute_input":"2022-04-14T19:25:00.959603Z","iopub.status.idle":"2022-04-14T19:25:00.971338Z","shell.execute_reply.started":"2022-04-14T19:25:00.959568Z","shell.execute_reply":"2022-04-14T19:25:00.970349Z"},"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-14T19:25:00.973400Z","iopub.execute_input":"2022-04-14T19:25:00.974032Z","iopub.status.idle":"2022-04-14T19:25:01.163980Z","shell.execute_reply.started":"2022-04-14T19:25:00.973993Z","shell.execute_reply":"2022-04-14T19:25:01.163285Z"},"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-14T19:25:01.165154Z","iopub.execute_input":"2022-04-14T19:25:01.165386Z","iopub.status.idle":"2022-04-14T19:25:01.176311Z","shell.execute_reply.started":"2022-04-14T19:25:01.165351Z","shell.execute_reply":"2022-04-14T19:25:01.175616Z"},"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-14T19:25:01.177254Z","iopub.execute_input":"2022-04-14T19:25:01.177485Z","iopub.status.idle":"2022-04-14T19:25:01.935438Z","shell.execute_reply.started":"2022-04-14T19:25:01.177455Z","shell.execute_reply":"2022-04-14T19:25:01.933483Z"},"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-14T19:25:01.937060Z","iopub.execute_input":"2022-04-14T19:25:01.937624Z","iopub.status.idle":"2022-04-14T19:25:01.947686Z","shell.execute_reply.started":"2022-04-14T19:25:01.937578Z","shell.execute_reply":"2022-04-14T19:25:01.945885Z"},"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-14T19:25:01.950828Z","iopub.execute_input":"2022-04-14T19:25:01.952795Z","iopub.status.idle":"2022-04-14T19:25:02.392916Z","shell.execute_reply.started":"2022-04-14T19:25:01.952748Z","shell.execute_reply":"2022-04-14T19:25:02.392199Z"},"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-14T19:25:02.399929Z","iopub.execute_input":"2022-04-14T19:25:02.402087Z","iopub.status.idle":"2022-04-14T19:25:02.804953Z","shell.execute_reply.started":"2022-04-14T19:25:02.402042Z","shell.execute_reply":"2022-04-14T19:25:02.804229Z"},"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-14T19:25:02.806144Z","iopub.execute_input":"2022-04-14T19:25:02.806919Z","iopub.status.idle":"2022-04-14T19:25:02.826900Z","shell.execute_reply.started":"2022-04-14T19:25:02.806875Z","shell.execute_reply":"2022-04-14T19:25:02.826268Z"},"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-14T19:25:02.828397Z","iopub.execute_input":"2022-04-14T19:25:02.829005Z","iopub.status.idle":"2022-04-14T19:25:03.070083Z","shell.execute_reply.started":"2022-04-14T19:25:02.828936Z","shell.execute_reply":"2022-04-14T19:25:03.069144Z"},"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-14T19:25:03.071730Z","iopub.execute_input":"2022-04-14T19:25:03.072020Z","iopub.status.idle":"2022-04-14T19:25:03.078541Z","shell.execute_reply.started":"2022-04-14T19:25:03.071980Z","shell.execute_reply":"2022-04-14T19:25:03.077690Z"},"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-14T19:25:03.080202Z","iopub.execute_input":"2022-04-14T19:25:03.080796Z","iopub.status.idle":"2022-04-14T19:25:03.395535Z","shell.execute_reply.started":"2022-04-14T19:25:03.080753Z","shell.execute_reply":"2022-04-14T19:25:03.394838Z"},"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-14T19:25:03.396791Z","iopub.execute_input":"2022-04-14T19:25:03.397204Z","iopub.status.idle":"2022-04-14T19:25:03.727067Z","shell.execute_reply.started":"2022-04-14T19:25:03.397166Z","shell.execute_reply":"2022-04-14T19:25:03.726346Z"},"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-14T19:25:03.728442Z","iopub.execute_input":"2022-04-14T19:25:03.728910Z","iopub.status.idle":"2022-04-14T19:25:03.744215Z","shell.execute_reply.started":"2022-04-14T19:25:03.728872Z","shell.execute_reply":"2022-04-14T19:25:03.743514Z"},"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-14T19:25:03.745390Z","iopub.execute_input":"2022-04-14T19:25:03.745738Z","iopub.status.idle":"2022-04-14T19:25:07.527895Z","shell.execute_reply.started":"2022-04-14T19:25:03.745700Z","shell.execute_reply":"2022-04-14T19:25:07.526229Z"},"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,87)\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-14T19:25:07.529102Z","iopub.execute_input":"2022-04-14T19:25:07.529544Z","iopub.status.idle":"2022-04-14T19:25:07.634263Z","shell.execute_reply.started":"2022-04-14T19:25:07.529484Z","shell.execute_reply":"2022-04-14T19:25:07.633574Z"},"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-14T19:25:07.635544Z","iopub.execute_input":"2022-04-14T19:25:07.636094Z","iopub.status.idle":"2022-04-14T19:25:07.668322Z","shell.execute_reply.started":"2022-04-14T19:25:07.636054Z","shell.execute_reply":"2022-04-14T19:25:07.667552Z"},"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-14T19:25:07.669751Z","iopub.execute_input":"2022-04-14T19:25:07.670235Z","iopub.status.idle":"2022-04-14T19:25:07.675379Z","shell.execute_reply.started":"2022-04-14T19:25:07.670199Z","shell.execute_reply":"2022-04-14T19:25:07.674574Z"},"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-14T19:25:07.676743Z","iopub.execute_input":"2022-04-14T19:25:07.677471Z","iopub.status.idle":"2022-04-14T19:25:07.684998Z","shell.execute_reply.started":"2022-04-14T19:25:07.677430Z","shell.execute_reply":"2022-04-14T19:25:07.684031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building CNN","metadata":{}},{"cell_type":"code","source":"ENB1_model = efn.EfficientNetB1(input_shape=(128,87,3), include_top=False, weights='imagenet')\nENB1_model.trainable = True","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:25:07.687217Z","iopub.execute_input":"2022-04-14T19:25:07.688466Z","iopub.status.idle":"2022-04-14T19:25:10.828254Z","shell.execute_reply.started":"2022-04-14T19:25:07.688416Z","shell.execute_reply":"2022-04-14T19:25:10.827417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    ENB1_model,\n    \n    Flatten(),\n    \n    Dense(64, activation='relu'),\n    Dropout(0.45),\n    \n    Dense(32, activation='relu'),\n    Dropout(0.45),\n    \n    Dense(41, activation='softmax')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:25:10.829866Z","iopub.execute_input":"2022-04-14T19:25:10.830151Z","iopub.status.idle":"2022-04-14T19:25:11.573919Z","shell.execute_reply.started":"2022-04-14T19:25:10.830111Z","shell.execute_reply":"2022-04-14T19:25:11.573218Z"},"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-14T19:25:11.575346Z","iopub.execute_input":"2022-04-14T19:25:11.575627Z","iopub.status.idle":"2022-04-14T19:25:11.595373Z","shell.execute_reply.started":"2022-04-14T19:25:11.575591Z","shell.execute_reply":"2022-04-14T19:25:11.594683Z"},"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)\n","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:25:11.597305Z","iopub.execute_input":"2022-04-14T19:25:11.598029Z","iopub.status.idle":"2022-04-14T19:33:20.976896Z","shell.execute_reply.started":"2022-04-14T19:25:11.597989Z","shell.execute_reply":"2022-04-14T19:33:20.976095Z"},"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-14T19:33:20.978710Z","iopub.execute_input":"2022-04-14T19:33:20.979141Z","iopub.status.idle":"2022-04-14T19:33:20.984765Z","shell.execute_reply.started":"2022-04-14T19:33:20.979101Z","shell.execute_reply":"2022-04-14T19:33:20.984120Z"},"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-14T19:33:20.986336Z","iopub.execute_input":"2022-04-14T19:33:20.986690Z","iopub.status.idle":"2022-04-14T19:33:20.995758Z","shell.execute_reply.started":"2022-04-14T19:33:20.986653Z","shell.execute_reply":"2022-04-14T19:33:20.994875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:33:20.997386Z","iopub.execute_input":"2022-04-14T19:33:20.997696Z","iopub.status.idle":"2022-04-14T19:33:21.406084Z","shell.execute_reply.started":"2022-04-14T19:33:20.997660Z","shell.execute_reply":"2022-04-14T19:33:21.405317Z"},"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-14T19:33:21.407553Z","iopub.execute_input":"2022-04-14T19:33:21.407827Z","iopub.status.idle":"2022-04-14T19:33:21.412891Z","shell.execute_reply.started":"2022-04-14T19:33:21.407788Z","shell.execute_reply":"2022-04-14T19:33:21.412170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh2 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 10, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:33:21.414076Z","iopub.execute_input":"2022-04-14T19:33:21.414589Z","iopub.status.idle":"2022-04-14T19:37:10.960553Z","shell.execute_reply.started":"2022-04-14T19:33:21.414550Z","shell.execute_reply":"2022-04-14T19:37:10.959823Z"},"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-14T19:37:10.965151Z","iopub.execute_input":"2022-04-14T19:37:10.965377Z","iopub.status.idle":"2022-04-14T19:37:10.975230Z","shell.execute_reply.started":"2022-04-14T19:37:10.965349Z","shell.execute_reply":"2022-04-14T19:37:10.974386Z"},"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-14T19:37:10.976795Z","iopub.execute_input":"2022-04-14T19:37:10.977078Z","iopub.status.idle":"2022-04-14T19:37:11.400194Z","shell.execute_reply.started":"2022-04-14T19:37:10.977039Z","shell.execute_reply":"2022-04-14T19:37:11.399294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training Run 3","metadata":{}},{"cell_type":"code","source":"K.set_value(cnn.optimizer.learning_rate, 0.00001)","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:37:11.401375Z","iopub.execute_input":"2022-04-14T19:37:11.402029Z","iopub.status.idle":"2022-04-14T19:37:11.407230Z","shell.execute_reply.started":"2022-04-14T19:37:11.401986Z","shell.execute_reply":"2022-04-14T19:37:11.406280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time \n\nh3 = cnn.fit(train_loader, steps_per_epoch = TR_STEPS, epochs = 10, validation_data = valid_loader, \n             validation_steps = VA_STEPS, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:37:11.408789Z","iopub.execute_input":"2022-04-14T19:37:11.409204Z","iopub.status.idle":"2022-04-14T19:41:19.321162Z","shell.execute_reply.started":"2022-04-14T19:37:11.409167Z","shell.execute_reply":"2022-04-14T19:41:19.320375Z"},"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-14T19:41:19.323022Z","iopub.execute_input":"2022-04-14T19:41:19.323523Z","iopub.status.idle":"2022-04-14T19:41:19.331479Z","shell.execute_reply.started":"2022-04-14T19:41:19.323468Z","shell.execute_reply":"2022-04-14T19:41:19.330716Z"},"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-14T19:41:19.332988Z","iopub.execute_input":"2022-04-14T19:41:19.333400Z","iopub.status.idle":"2022-04-14T19:41:19.704999Z","shell.execute_reply.started":"2022-04-14T19:41:19.333362Z","shell.execute_reply":"2022-04-14T19:41:19.704360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"cnn.save(f'Freesound_Audio_EfficientNet_B1_v01.h5')","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:41:19.709157Z","iopub.execute_input":"2022-04-14T19:41:19.709364Z","iopub.status.idle":"2022-04-14T19:41:20.627521Z","shell.execute_reply.started":"2022-04-14T19:41:19.709332Z","shell.execute_reply":"2022-04-14T19:41:20.626754Z"},"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-14T19:41:20.629166Z","iopub.execute_input":"2022-04-14T19:41:20.629450Z","iopub.status.idle":"2022-04-14T19:42:29.062607Z","shell.execute_reply.started":"2022-04-14T19:41:20.629414Z","shell.execute_reply":"2022-04-14T19:42:29.061821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(probs[0, :].round(2))","metadata":{"execution":{"iopub.status.busy":"2022-04-14T19:42:29.064179Z","iopub.execute_input":"2022-04-14T19:42:29.064708Z","iopub.status.idle":"2022-04-14T19:42:29.071770Z","shell.execute_reply.started":"2022-04-14T19:42:29.064668Z","shell.execute_reply":"2022-04-14T19:42:29.071071Z"},"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-14T19:42:29.073044Z","iopub.execute_input":"2022-04-14T19:42:29.073655Z","iopub.status.idle":"2022-04-14T19:42:29.817146Z","shell.execute_reply.started":"2022-04-14T19:42:29.073616Z","shell.execute_reply":"2022-04-14T19:42:29.816359Z"},"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-14T19:42:29.819342Z","iopub.execute_input":"2022-04-14T19:42:29.819909Z","iopub.status.idle":"2022-04-14T19:42:30.745038Z","shell.execute_reply.started":"2022-04-14T19:42:29.819860Z","shell.execute_reply":"2022-04-14T19:42:30.744366Z"},"trusted":true},"execution_count":null,"outputs":[]}]}