{"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-01T02:08:55.52246Z","iopub.execute_input":"2022-04-01T02:08:55.522912Z","iopub.status.idle":"2022-04-01T02:08:55.5316Z","shell.execute_reply.started":"2022-04-01T02:08:55.522865Z","shell.execute_reply":"2022-04-01T02:08:55.530617Z"},"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-01T02:08:55.533344Z","iopub.execute_input":"2022-04-01T02:08:55.534921Z","iopub.status.idle":"2022-04-01T02:08:55.548686Z","shell.execute_reply.started":"2022-04-01T02:08:55.534879Z","shell.execute_reply":"2022-04-01T02:08:55.547578Z"},"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-04-01T02:08:55.550865Z","iopub.execute_input":"2022-04-01T02:08:55.551812Z","iopub.status.idle":"2022-04-01T02:08:55.574613Z","shell.execute_reply.started":"2022-04-01T02:08:55.551669Z","shell.execute_reply":"2022-04-01T02:08:55.573701Z"},"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-01T02:08:55.579256Z","iopub.execute_input":"2022-04-01T02:08:55.579447Z","iopub.status.idle":"2022-04-01T02:08:56.003526Z","shell.execute_reply.started":"2022-04-01T02:08:55.579423Z","shell.execute_reply":"2022-04-01T02:08:56.002714Z"},"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, 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        \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-04-01T02:08:56.004709Z","iopub.execute_input":"2022-04-01T02:08:56.006105Z","iopub.status.idle":"2022-04-01T02:08:56.03418Z","shell.execute_reply.started":"2022-04-01T02:08:56.006063Z","shell.execute_reply":"2022-04-01T02:08:56.033145Z"},"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-04-01T02:08:56.035675Z","iopub.execute_input":"2022-04-01T02:08:56.036Z","iopub.status.idle":"2022-04-01T02:08:56.15341Z","shell.execute_reply.started":"2022-04-01T02:08:56.035903Z","shell.execute_reply":"2022-04-01T02:08:56.152616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(1)\ncnn = Sequential()\n\ncnn.add(Conv2D(32, (3,3), activation = 'elu', padding = 'same', input_shape=(69,65,3)))\ncnn.add(Conv2D(32, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(MaxPooling2D(2,2))\ncnn.add(Dropout(0.20))\ncnn.add(BatchNormalization())\n\ncnn.add(Conv2D(64, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(Conv2D(64, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(MaxPooling2D(2,2))\ncnn.add(Dropout(0.20))\ncnn.add(BatchNormalization())\n\ncnn.add(Conv2D(128, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(Conv2D(128, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(MaxPooling2D(2,2))\ncnn.add(Dropout(0.20))\ncnn.add(BatchNormalization())\n\ncnn.add(Conv2D(128, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(Conv2D(128, (3,3), activation = 'elu', padding = 'same'))\ncnn.add(Dropout(0.20))\ncnn.add(BatchNormalization())\n\ncnn.add(Flatten())\n\ncnn.add(Dense(128, activation='elu'))\ncnn.add(Dropout(0.20))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(64, activation='elu'))\ncnn.add(Dropout(0.10))\ncnn.add(BatchNormalization())\n\ncnn.add(Dense(1, activation='sigmoid'))\n\ncnn.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-01T02:08:56.154911Z","iopub.execute_input":"2022-04-01T02:08:56.155206Z","iopub.status.idle":"2022-04-01T02:08:56.35408Z","shell.execute_reply.started":"2022-04-01T02:08:56.155169Z","shell.execute_reply":"2022-04-01T02:08:56.353336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nopt = tf.keras.optimizers.SGD(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-04-01T02:08:56.356871Z","iopub.execute_input":"2022-04-01T02:08:56.357101Z","iopub.status.idle":"2022-04-01T11:43:55.656758Z","shell.execute_reply.started":"2022-04-01T02:08:56.357075Z","shell.execute_reply":"2022-04-01T11:43:55.654757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = merge_history([h1])\nvis_training(history)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T12:17:22.832974Z","iopub.execute_input":"2022-04-01T12:17:22.833317Z","iopub.status.idle":"2022-04-01T12:17:23.284463Z","shell.execute_reply.started":"2022-04-01T12:17:22.833276Z","shell.execute_reply":"2022-04-01T12:17:23.283794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SPEC_PATH = '../input/g2net-q-transform-69x65/images'\n\nclass DataGenerator2(keras.utils.Sequence):\n    \n    def __init__(self, df, batch_size=32, 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        \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 = 'test' if self.is_train else 'train'\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-01T11:43:56.244097Z","iopub.execute_input":"2022-04-01T11:43:56.244461Z","iopub.status.idle":"2022-04-01T11:43:56.304227Z","shell.execute_reply.started":"2022-04-01T11:43:56.244427Z","shell.execute_reply":"2022-04-01T11:43:56.303515Z"},"trusted":true},"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":{"iopub.status.busy":"2022-04-01T11:43:56.30535Z","iopub.execute_input":"2022-04-01T11:43:56.305603Z","iopub.status.idle":"2022-04-01T11:43:56.531823Z","shell.execute_reply.started":"2022-04-01T11:43:56.305568Z","shell.execute_reply":"2022-04-01T11:43:56.531009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loader = DataGenerator2(test, batch_size=2048, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T11:43:56.533018Z","iopub.execute_input":"2022-04-01T11:43:56.533339Z","iopub.status.idle":"2022-04-01T11:43:56.538217Z","shell.execute_reply.started":"2022-04-01T11:43:56.533301Z","shell.execute_reply":"2022-04-01T11:43:56.537449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_prob = cnn.predict(test_loader)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T11:43:56.539565Z","iopub.execute_input":"2022-04-01T11:43:56.540053Z","iopub.status.idle":"2022-04-01T12:17:17.848091Z","shell.execute_reply.started":"2022-04-01T11:43:56.540014Z","shell.execute_reply":"2022-04-01T12:17:17.847211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn.save('CQT2.h')","metadata":{"execution":{"iopub.status.busy":"2022-04-01T12:17:17.849457Z","iopub.execute_input":"2022-04-01T12:17:17.849733Z","iopub.status.idle":"2022-04-01T12:17:22.079776Z","shell.execute_reply.started":"2022-04-01T12:17:17.849698Z","shell.execute_reply":"2022-04-01T12:17:22.079061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_prob)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T12:17:22.0911Z","iopub.execute_input":"2022-04-01T12:17:22.091314Z","iopub.status.idle":"2022-04-01T12:17:22.095658Z","shell.execute_reply.started":"2022-04-01T12:17:22.091287Z","shell.execute_reply":"2022-04-01T12:17:22.094832Z"},"trusted":true},"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":{"iopub.status.busy":"2022-04-01T12:17:22.096931Z","iopub.execute_input":"2022-04-01T12:17:22.097635Z","iopub.status.idle":"2022-04-01T12:17:22.280605Z","shell.execute_reply.started":"2022-04-01T12:17:22.097589Z","shell.execute_reply":"2022-04-01T12:17:22.279809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submissionqformCQT.csv', header=True, index= False)","metadata":{"execution":{"iopub.status.busy":"2022-04-01T12:17:22.281969Z","iopub.execute_input":"2022-04-01T12:17:22.282219Z","iopub.status.idle":"2022-04-01T12:17:22.830371Z","shell.execute_reply.started":"2022-04-01T12:17:22.282185Z","shell.execute_reply":"2022-04-01T12:17:22.829611Z"},"trusted":true},"execution_count":null,"outputs":[]}]}