{"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":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pandas as pd\nimport math\nimport cv2\nimport librosa \nimport librosa.display\nimport IPython.display as ipd \nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras import backend as K","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-27T02:40:00.355991Z","iopub.execute_input":"2022-03-27T02:40:00.356241Z","iopub.status.idle":"2022-03-27T02:40:06.935037Z","shell.execute_reply.started":"2022-03-27T02:40:00.356213Z","shell.execute_reply":"2022-03-27T02:40:06.934238Z"},"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-03-27T02:37:25.606966Z","iopub.execute_input":"2022-03-27T02:37:25.607218Z","iopub.status.idle":"2022-03-27T02:37:25.611791Z","shell.execute_reply.started":"2022-03-27T02:37:25.607191Z","shell.execute_reply":"2022-03-27T02:37:25.610965Z"},"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=[16,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-03-27T02:37:28.883922Z","iopub.execute_input":"2022-03-27T02:37:28.884659Z","iopub.status.idle":"2022-03-27T02:37:28.893794Z","shell.execute_reply.started":"2022-03-27T02:37:28.884620Z","shell.execute_reply":"2022-03-27T02:37:28.893012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/g2net-q-transform-69x129/images/training_labels.csv')\nprint(train.shape, '\\n')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:40:10.834290Z","iopub.execute_input":"2022-03-27T02:40:10.834966Z","iopub.status.idle":"2022-03-27T02:40:11.203844Z","shell.execute_reply.started":"2022-03-27T02:40:10.834927Z","shell.execute_reply":"2022-03-27T02:40:11.202622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SPEC_PATH = '../input/g2net-q-transform-69x129/images'\n\nclass DataGenerator(keras.utils.Sequence):\n    \n    def __init__(self, df, batch_size=32, img_size=(69,129), shuffle=True, is_train=True):\n        self.df = df\n        self.n = len(df)\n        self.batch_size = batch_size\n        self.img_size = img_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        return math.ceil( self.n / self.batch_size )\n    \n    def __getitem__(self, batch_index):\n        start = batch_index * self.batch_size\n        end = (batch_index + 1) * self.batch_size\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, self.img_size[0], self.img_size[1], 3))\n        y = np.zeros(batch_size)\n        \n        for i, idx in enumerate(batch_indices):\n            ID = self.df.id.values[idx]\n            y[i] = self.df.target.values[idx]\n            \n            SET = 'train' if self.is_train else 'test'\n            path = f'{SPEC_PATH}/{SET}/{ID}.npy'\n            data_array = np.load(path)\n            \n            X[i,:,:,:] = data_array\n            \n        return X, y\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)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:41:15.159198Z","iopub.execute_input":"2022-03-27T02:41:15.159488Z","iopub.status.idle":"2022-03-27T02:41:15.223385Z","shell.execute_reply.started":"2022-03-27T02:41:15.159458Z","shell.execute_reply":"2022-03-27T02:41:15.222676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, valid_df = train_test_split(train, test_size=0.15)\ntrain_loader = DataGenerator(train_df, batch_size=2048, shuffle=True)\nvalid_loader = DataGenerator(valid_df, batch_size=2048, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:41:32.352689Z","iopub.execute_input":"2022-03-27T02:41:32.353484Z","iopub.status.idle":"2022-03-27T02:41:32.467663Z","shell.execute_reply.started":"2022-03-27T02:41:32.353439Z","shell.execute_reply":"2022-03-27T02:41:32.466782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = tf.keras.applications.VGG16(input_shape=(69,129,3),\n                                         include_top=False,\n                                         weights='imagenet')\n\nbase_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:43:08.393750Z","iopub.execute_input":"2022-03-27T02:43:08.394012Z","iopub.status.idle":"2022-03-27T02:43:11.801048Z","shell.execute_reply.started":"2022-03-27T02:43:08.393984Z","shell.execute_reply":"2022-03-27T02:43:11.800238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    base_model,\n    \n    Flatten(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.2),\n    Dense(64, activation='relu'),\n    Dropout(0.1),\n    BatchNormalization(),\n    Dense(1, activation='sigmoid')\n])\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:44:32.687429Z","iopub.execute_input":"2022-03-27T02:44:32.687926Z","iopub.status.idle":"2022-03-27T02:44:32.788645Z","shell.execute_reply.started":"2022-03-27T02:44:32.687888Z","shell.execute_reply":"2022-03-27T02:44:32.787974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nopt = tf.keras.optimizers.Adam(0.01)\ncnn.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])\n\nh1 = cnn.fit(train_loader, epochs=10, validation_data=valid_loader, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T02:45:39.676499Z","iopub.execute_input":"2022-03-27T02:45:39.677072Z","iopub.status.idle":"2022-03-27T12:44:12.405844Z","shell.execute_reply.started":"2022-03-27T02:45:39.677033Z","shell.execute_reply":"2022-03-27T12:44:12.402954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-03-27T12:49:52.743816Z","iopub.execute_input":"2022-03-27T12:49:52.745302Z","iopub.status.idle":"2022-03-27T12:49:53.538680Z","shell.execute_reply.started":"2022-03-27T12:49:52.745258Z","shell.execute_reply":"2022-03-27T12:49:53.538001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}