{"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 tensorflow as tf\nimport os\nimport random\nimport numpy as np\n \nfrom tqdm import tqdm \n\nfrom skimage.io import imread, imshow\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:34:43.211434Z","iopub.execute_input":"2022-12-19T12:34:43.211798Z","iopub.status.idle":"2022-12-19T12:34:48.612986Z","shell.execute_reply.started":"2022-12-19T12:34:43.211762Z","shell.execute_reply":"2022-12-19T12:34:48.612056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from zipfile import ZipFile\nwith ZipFile(\"../input/data-science-bowl-2018/stage1_train.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"./stage1_train\")\n    \nwith ZipFile(\"../input/data-science-bowl-2018/stage1_test.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"./stage1_test\")","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:34:48.614501Z","iopub.execute_input":"2022-12-19T12:34:48.615132Z","iopub.status.idle":"2022-12-19T12:34:54.708137Z","shell.execute_reply.started":"2022-12-19T12:34:48.615095Z","shell.execute_reply":"2022-12-19T12:34:54.707088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed = 42\nnp.random.seed = seed\n\nIMG_WIDTH = 128\nIMG_HEIGHT = 128\nIMG_CHANNELS = 3\n\nTRAIN_PATH = 'stage1_train/'\nTEST_PATH = 'stage1_test/'\n\ntrain_ids = next(os.walk(TRAIN_PATH))[1]\ntest_ids = next(os.walk(TEST_PATH))[1]\n\nX = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\ny = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, 1), dtype=bool)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:34:54.71216Z","iopub.execute_input":"2022-12-19T12:34:54.712486Z","iopub.status.idle":"2022-12-19T12:34:54.721304Z","shell.execute_reply.started":"2022-12-19T12:34:54.712458Z","shell.execute_reply":"2022-12-19T12:34:54.720346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Resizing training images and masks')\nfor n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)):   \n    path = TRAIN_PATH + id_\n    img = imread(path + '/images/' + id_ + '.png')[:,:,:IMG_CHANNELS]  \n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    X[n] = img  #Fill empty X_train with values from img\n    mask = np.zeros((IMG_HEIGHT, IMG_WIDTH, 1), dtype=bool)\n    for mask_file in next(os.walk(path + '/masks/'))[2]:\n        mask_ = imread(path + '/masks/' + mask_file)\n        mask_ = np.expand_dims(resize(mask_, (IMG_HEIGHT, IMG_WIDTH), mode='constant',  \n                                      preserve_range=True), axis=-1)\n        mask = np.maximum(mask, mask_)  \n            \n    y[n] = mask ","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:35:05.422033Z","iopub.execute_input":"2022-12-19T12:35:05.42244Z","iopub.status.idle":"2022-12-19T12:39:14.425548Z","shell.execute_reply.started":"2022-12-19T12:35:05.422386Z","shell.execute_reply":"2022-12-19T12:39:14.424473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:14.427718Z","iopub.execute_input":"2022-12-19T12:39:14.429695Z","iopub.status.idle":"2022-12-19T12:39:14.446085Z","shell.execute_reply.started":"2022-12-19T12:39:14.42965Z","shell.execute_reply":"2022-12-19T12:39:14.444931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test images\ntest_images = np.zeros((len(test_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nsizes_test = []\nprint('Resizing test images') \nfor n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):\n    path = TEST_PATH + id_\n    img = imread(path + '/images/' + id_ + '.png')[:,:,:IMG_CHANNELS]\n    sizes_test.append([img.shape[0], img.shape[1]])\n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    test_images[n] = img\n\nprint('Done!')","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:14.447476Z","iopub.execute_input":"2022-12-19T12:39:14.448028Z","iopub.status.idle":"2022-12-19T12:39:15.746889Z","shell.execute_reply.started":"2022-12-19T12:39:14.447991Z","shell.execute_reply":"2022-12-19T12:39:15.744711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_x = random.randint(0, len(X_train))\nplt.axis(\"off\")\nimshow(X_train[image_x])\nplt.show()\nplt.axis(\"off\")\nimshow(np.squeeze(y_train[image_x]))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-18T06:49:02.244658Z","iopub.execute_input":"2022-12-18T06:49:02.245328Z","iopub.status.idle":"2022-12-18T06:49:02.55701Z","shell.execute_reply.started":"2022-12-18T06:49:02.24529Z","shell.execute_reply":"2022-12-18T06:49:02.555774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = 1","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:15.749921Z","iopub.execute_input":"2022-12-19T12:39:15.750645Z","iopub.status.idle":"2022-12-19T12:39:15.755655Z","shell.execute_reply.started":"2022-12-19T12:39:15.750604Z","shell.execute_reply":"2022-12-19T12:39:15.754463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Build the model\ninputs = tf.keras.layers.Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))\n\n#Contraction path\nc1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(inputs)\nc1 = tf.keras.layers.Dropout(0.1)(c1)\nc1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c1)\nb1 = tf.keras.layers.BatchNormalization()(c1)\nr1 = tf.keras.layers.ReLU()(b1)\np1 = tf.keras.layers.MaxPooling2D((2, 2))(r1)\n\nc2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p1)\nc2 = tf.keras.layers.Dropout(0.1)(c2)\nc2 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c2)\nb2 = tf.keras.layers.BatchNormalization()(c2)\nr2 = tf.keras.layers.ReLU()(b2)\np2 = tf.keras.layers.MaxPooling2D((2, 2))(r2)\n \nc3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p2)\nc3 = tf.keras.layers.Dropout(0.2)(c3)\nc3 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c3)\nb3 = tf.keras.layers.BatchNormalization()(c3)\nr3 = tf.keras.layers.ReLU()(b3)\np3 = tf.keras.layers.MaxPooling2D((2, 2))(r3)\n \nc4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p3)\nc4 = tf.keras.layers.Dropout(0.2)(c4)\nc4 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c4)\nb4 = tf.keras.layers.BatchNormalization()(c4)\nr4 = tf.keras.layers.ReLU()(b4)\np4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(r4)\n \nc5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p4)\nb5 = tf.keras.layers.BatchNormalization()(c5)\nr5 = tf.keras.layers.ReLU()(b5)\nc5 = tf.keras.layers.Dropout(0.3)(r5)\nc5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c5)\n\n#Expansive path \nu6 = tf.keras.layers.Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(c5)\nu6 = tf.keras.layers.concatenate([u6, c4])\nu6 = tf.keras.layers.BatchNormalization()(u6)\nu6 = tf.keras.layers.ReLU()(u6)\n\n \nu7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(u6)\nu7 = tf.keras.layers.concatenate([u7, c3])\nu7 = tf.keras.layers.BatchNormalization()(u7)\nu7 = tf.keras.layers.ReLU()(u7)\n\n \nu8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(u7)\nu8 = tf.keras.layers.concatenate([u8, c2])\nu8 = tf.keras.layers.BatchNormalization()(u8)\nu8 = tf.keras.layers.ReLU()(u8)\n \nu9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(u8)\nu9 = tf.keras.layers.concatenate([u9, c1], axis=3)\nu9 = tf.keras.layers.BatchNormalization()(u9)\nu9 = tf.keras.layers.ReLU()(u9)\n\n \noutputs = tf.keras.layers.Conv2D(num_classes, (1, 1), activation='sigmoid')(u9)\n \nmodel = tf.keras.Model(inputs=[inputs], outputs=[outputs])\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:15.757285Z","iopub.execute_input":"2022-12-19T12:39:15.757921Z","iopub.status.idle":"2022-12-19T12:39:20.089987Z","shell.execute_reply.started":"2022-12-19T12:39:15.757861Z","shell.execute_reply":"2022-12-19T12:39:20.088938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(model, \"model.png\")","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:20.091488Z","iopub.execute_input":"2022-12-19T12:39:20.092094Z","iopub.status.idle":"2022-12-19T12:39:21.334169Z","shell.execute_reply.started":"2022-12-19T12:39:20.092055Z","shell.execute_reply":"2022-12-19T12:39:21.333091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [\n        tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),\n        tf.keras.callbacks.TensorBoard(log_dir='logs')]\n\nmodel.fit(X_train, y_train, validation_data=(X_test,y_test), batch_size=16, epochs=25, callbacks=callbacks)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:21.335565Z","iopub.execute_input":"2022-12-19T12:39:21.336473Z","iopub.status.idle":"2022-12-19T12:39:44.485126Z","shell.execute_reply.started":"2022-12-19T12:39:21.336431Z","shell.execute_reply":"2022-12-19T12:39:44.484222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss = model.history.history['loss']\nval_loss = model.history.history['val_loss']\n\nplt.figure()\nplt.plot( loss, 'r', label='Training loss')\nplt.plot( val_loss, 'bo', label='Validation loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss Value')\nplt.ylim([0, 1])\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:39:54.525197Z","iopub.execute_input":"2022-12-19T12:39:54.525574Z","iopub.status.idle":"2022-12-19T12:39:54.739472Z","shell.execute_reply.started":"2022-12-19T12:39:54.525542Z","shell.execute_reply":"2022-12-19T12:39:54.738423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy = model.history.history['accuracy']\nval_accuracy = model.history.history['val_accuracy']\n\nplt.figure()\nplt.plot( accuracy, 'r', label='Training accuracy')\nplt.plot( val_accuracy, 'bo', label='Validation accuracy')\nplt.title('Training and Validation accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Loss Value')\nplt.ylim([0, 1])\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:02.988849Z","iopub.execute_input":"2022-12-19T12:40:02.989531Z","iopub.status.idle":"2022-12-19T12:40:03.205294Z","shell.execute_reply.started":"2022-12-19T12:40:02.989492Z","shell.execute_reply":"2022-12-19T12:40:03.204355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display(display_list):\n  plt.figure(figsize=(15, 15))\n\n  title = ['Input image', 'True mask', 'Predicted mask']\n\n  for i in range(len(display_list)):\n    plt.subplot(1, len(display_list), i+1)\n    plt.title(title[i])\n    plt.imshow(tf.keras.utils.array_to_img(display_list[i]))\n    plt.axis('off')\n  plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:08.582768Z","iopub.execute_input":"2022-12-19T12:40:08.583367Z","iopub.status.idle":"2022-12-19T12:40:08.589633Z","shell.execute_reply.started":"2022-12-19T12:40:08.583321Z","shell.execute_reply":"2022-12-19T12:40:08.588623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = random.randint(0, len(X_test))\nsample_image = X_test[i]\nsample_mask = y_test[i]","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:11.715323Z","iopub.execute_input":"2022-12-19T12:40:11.715695Z","iopub.status.idle":"2022-12-19T12:40:11.720716Z","shell.execute_reply.started":"2022-12-19T12:40:11.715664Z","shell.execute_reply":"2022-12-19T12:40:11.719542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"prediction = model.predict(sample_image[tf.newaxis, ...])[0]","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:15.146296Z","iopub.execute_input":"2022-12-19T12:40:15.146999Z","iopub.status.idle":"2022-12-19T12:40:15.510082Z","shell.execute_reply.started":"2022-12-19T12:40:15.146962Z","shell.execute_reply":"2022-12-19T12:40:15.509043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_mask = (prediction > 0.5).astype(np.uint8)","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:27.320204Z","iopub.execute_input":"2022-12-19T12:40:27.320584Z","iopub.status.idle":"2022-12-19T12:40:27.326096Z","shell.execute_reply.started":"2022-12-19T12:40:27.320551Z","shell.execute_reply":"2022-12-19T12:40:27.324999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display([sample_image, sample_mask,predicted_mask])","metadata":{"execution":{"iopub.status.busy":"2022-12-19T12:40:30.942994Z","iopub.execute_input":"2022-12-19T12:40:30.943364Z","iopub.status.idle":"2022-12-19T12:40:31.206223Z","shell.execute_reply.started":"2022-12-19T12:40:30.943332Z","shell.execute_reply":"2022-12-19T12:40:31.205266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}