{"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-04-11T18:48:26.472744Z","iopub.execute_input":"2022-04-11T18:48:26.473103Z","iopub.status.idle":"2022-04-11T18:48:34.010646Z","shell.execute_reply.started":"2022-04-11T18:48:26.473022Z","shell.execute_reply":"2022-04-11T18:48:34.009864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -U efficientnet -qq","metadata":{"execution":{"iopub.status.busy":"2022-04-11T18:49:13.20108Z","iopub.execute_input":"2022-04-11T18:49:13.201659Z","iopub.status.idle":"2022-04-11T18:49:22.951785Z","shell.execute_reply.started":"2022-04-11T18:49:13.201619Z","shell.execute_reply":"2022-04-11T18:49:22.950652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import efficientnet.tfkeras as efn","metadata":{"execution":{"iopub.status.busy":"2022-04-11T18:49:39.071046Z","iopub.execute_input":"2022-04-11T18:49:39.071703Z","iopub.status.idle":"2022-04-11T18:49:39.283514Z","shell.execute_reply.started":"2022-04-11T18:49:39.07166Z","shell.execute_reply":"2022-04-11T18:49:39.282563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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\n\ndef 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-04-01T00:29:39.259923Z","iopub.execute_input":"2022-04-01T00:29:39.260174Z","iopub.status.idle":"2022-04-01T00:29:39.268705Z","shell.execute_reply.started":"2022-04-01T00:29:39.26014Z","shell.execute_reply":"2022-04-01T00:29:39.268118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/g2net-q-transform-69x65/images/training_labels.csv')\nprint(train.shape, '\\n')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-04-01T00:29:39.269732Z","iopub.execute_input":"2022-04-01T00:29:39.270134Z","iopub.status.idle":"2022-04-01T00:29:39.679711Z","shell.execute_reply.started":"2022-04-01T00:29:39.270097Z","shell.execute_reply":"2022-04-01T00:29:39.678733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SPEC_PATH = '../input/g2net-q-transform-69x65/images'\n\nclass DataGenerator(keras.utils.Sequence):\n    \n    def __init__(self, df, batch_size=32,n_batches = None, img_size=(69,65), 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        self.n_batches = n_batches\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        if self.n_batches is None:\n            return math.ceil( self.n / self.batch_size )\n        return self.n_batches\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-04-01T00:29:39.681774Z","iopub.execute_input":"2022-04-01T00:29:39.682093Z","iopub.status.idle":"2022-04-01T00:29:39.773458Z","shell.execute_reply.started":"2022-04-01T00:29:39.682056Z","shell.execute_reply":"2022-04-01T00:29:39.771871Z"},"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=64, shuffle=True)\nvalid_loader = DataGenerator(valid_df, batch_size=64, shuffle=True) #n_batch= x for lower number of batches","metadata":{"execution":{"iopub.status.busy":"2022-04-01T00:32:48.904083Z","iopub.execute_input":"2022-04-01T00:32:48.904367Z","iopub.status.idle":"2022-04-01T00:32:49.016774Z","shell.execute_reply.started":"2022-04-01T00:32:48.904337Z","shell.execute_reply":"2022-04-01T00:32:49.016011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = efn.EfficientNetB7(input_shape=(69,65,3), include_top=False, weights='imagenet')\n\n\n\nmodel.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-04-01T00:32:50.467151Z","iopub.execute_input":"2022-04-01T00:32:50.467999Z","iopub.status.idle":"2022-04-01T00:32:50.756082Z","shell.execute_reply.started":"2022-04-01T00:32:50.467951Z","shell.execute_reply":"2022-04-01T00:32:50.755358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = Sequential([\n    model,\n    \n    GlobalAveragePooling2D(),\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-04-01T00:32:56.286927Z","iopub.execute_input":"2022-04-01T00:32:56.287177Z","iopub.status.idle":"2022-04-01T00:32:56.385959Z","shell.execute_reply.started":"2022-04-01T00:32:56.287148Z","shell.execute_reply":"2022-04-01T00:32:56.385309Z"},"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=5, validation_data=valid_loader, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T00:32:59.144116Z","iopub.execute_input":"2022-04-01T00:32:59.144654Z","iopub.status.idle":"2022-04-01T01:21:50.94262Z","shell.execute_reply.started":"2022-04-01T00:32:59.144616Z","shell.execute_reply":"2022-04-01T01:21:50.941017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T01:46:06.232556Z","iopub.execute_input":"2022-04-01T01:46:06.232815Z","iopub.status.idle":"2022-04-01T01:46:06.247283Z","shell.execute_reply.started":"2022-04-01T01:46:06.232787Z","shell.execute_reply":"2022-04-01T01:46:06.246375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.trainable = True\n\nopt = tf.keras.optimizers.Adam(.0001)\ncnn.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy', tf.keras.metrics.AUC()])\n\nh2 = cnn.fit(train_loader, epochs=5, validation_data=valid_loader, verbose=1)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h2.history['auc'] = h2.history['auc_1']\nh2.history['val_auc'] = h2.history['val_auc_1']","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1,h2])\nvis_training(history, start = 5)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv('../input/g2net-q-transform-69x65/images/sample_submission.csv')\nprint(test.shape)\ntest.head()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loader = DataGenerator(test, batch_size=64, shuffle=False, is_train=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_prob = cnn.predict(test_loader)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.save('PBCQT1.h')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv('../input/g2net-q-transform-69x65/images/sample_submission.csv')\nsubmission.target = test_prob[:,0]\nsubmission","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submissionqformPBCQT.csv', header=True, index= False)","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":[]}]}