{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-04-13T19:43:24.115307Z","iopub.execute_input":"2022-04-13T19:43:24.115749Z","iopub.status.idle":"2022-04-13T19:43:24.150543Z","shell.execute_reply.started":"2022-04-13T19:43:24.1156Z","shell.execute_reply":"2022-04-13T19:43:24.149489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:24.152169Z","iopub.execute_input":"2022-04-13T19:43:24.152443Z","iopub.status.idle":"2022-04-13T19:43:30.796461Z","shell.execute_reply.started":"2022-04-13T19:43:24.152405Z","shell.execute_reply":"2022-04-13T19:43:30.795449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/data-science-bowl-2018/stage1_train.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"stage1_train\")\nwith zipfile.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-04-13T19:43:30.79795Z","iopub.execute_input":"2022-04-13T19:43:30.798263Z","iopub.status.idle":"2022-04-13T19:43:36.735271Z","shell.execute_reply.started":"2022-04-13T19:43:30.798221Z","shell.execute_reply":"2022-04-13T19:43:36.734478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed = 42\nnp.random.seed = seed\nTRAIN_PATH = 'stage1_train/'\nTEST_PATH = 'stage1_test/'\n","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:36.737147Z","iopub.execute_input":"2022-04-13T19:43:36.737468Z","iopub.status.idle":"2022-04-13T19:43:36.742091Z","shell.execute_reply.started":"2022-04-13T19:43:36.737423Z","shell.execute_reply":"2022-04-13T19:43:36.741054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nu_train = next(os.walk(TRAIN_PATH))[1]\nnu_test = next(os.walk(TEST_PATH))[1]","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:36.743119Z","iopub.execute_input":"2022-04-13T19:43:36.743361Z","iopub.status.idle":"2022-04-13T19:43:36.758266Z","shell.execute_reply.started":"2022-04-13T19:43:36.743335Z","shell.execute_reply":"2022-04-13T19:43:36.757354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids = next(os.walk(TRAIN_PATH))[1]\ntest_ids = next(os.walk(TEST_PATH))[1]","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:36.759479Z","iopub.execute_input":"2022-04-13T19:43:36.759704Z","iopub.status.idle":"2022-04-13T19:43:36.771406Z","shell.execute_reply.started":"2022-04-13T19:43:36.759678Z","shell.execute_reply":"2022-04-13T19:43:36.770465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainsetx = np.zeros((len(train_ids), 128, 128, 3), dtype=np.float16)\ntainsety = np.zeros((len(train_ids), 128, 128, 1), dtype=np.bool_)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:36.773115Z","iopub.execute_input":"2022-04-13T19:43:36.773491Z","iopub.status.idle":"2022-04-13T19:43:36.783764Z","shell.execute_reply.started":"2022-04-13T19:43:36.773433Z","shell.execute_reply":"2022-04-13T19:43:36.783019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for n, val in tqdm(enumerate(train_ids), total=len(train_ids)):  \n    # الان اصبح لدينا مسار يدخل الي /او  يتخطي الملف الاول ويدخل الي الملفين \n    path = 'stage1_train/' + val\n    # هنا نقوم بدمج المسار مع اسم من اسماء الملفات الموجوده في الملف الثاني حتي يستطيع الدخول اليها وتحويل نوع الصور التي يبدا في تكاراها الي نوع موحد من امتدادات الصور \n    img = imread(path + '/images/' + val + '.png')[:,:,:3]  \n    # بعدها يعمل علي اعاده تشكيل حجم الصوره الي الابعاد التي اشرنا اليها مسبقا \n    img = resize(img, (128, 128), mode='constant', preserve_range=True)\n    # بعدها مباشره نعمل علي تخزين تلك الصوره الناتجه داخل المصفوفه التي قمنا بانشاءها \n    trainsetx[n] = img  #Fill empty X_train with values from img\n    mask_data = np.zeros((128, 128, 1), dtype=np.bool_)\n    for mask_file in next(os.walk(path + '/masks/'))[2]:\n        maskt = imread(path + '/masks/' + mask_file)\n        maskt = np.expand_dims(resize(maskt, (128, 128), mode='constant',  \n                                      preserve_range=True), axis=-1)\n        mask = np.maximum(mask_data, maskt)  \n            \n    tainsety[n] = mask  ","metadata":{"execution":{"iopub.status.busy":"2022-04-13T19:43:36.785827Z","iopub.execute_input":"2022-04-13T19:43:36.786064Z","iopub.status.idle":"2022-04-13T19:48:39.943866Z","shell.execute_reply.started":"2022-04-13T19:43:36.786037Z","shell.execute_reply":"2022-04-13T19:48:39.942955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test images\ntestset = np.zeros((len(test_ids), 128, 128, 3), dtype=np.float32)\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')[:,:,:3]\n    sizes_test.append([img.shape[0], img.shape[1]])\n    img = resize(img, (128, 128), mode='constant', preserve_range=True)\n    testset[n] = img\n\nprint('Finish for train and test dataset!')","metadata":{"execution":{"iopub.status.busy":"2022-04-13T20:05:46.315953Z","iopub.execute_input":"2022-04-13T20:05:46.316382Z","iopub.status.idle":"2022-04-13T20:05:48.038928Z","shell.execute_reply.started":"2022-04-13T20:05:46.316349Z","shell.execute_reply":"2022-04-13T20:05:48.038116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"inputs = tf.keras.layers.Input((128, 128, 3))\ns = tf.keras.layers.Lambda(lambda x: x / 255)(inputs)\n#Contraction path\nc1 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(s)\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)\np1 = tf.keras.layers.MaxPooling2D((2, 2))(c1)\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)\np2 = tf.keras.layers.MaxPooling2D((2, 2))(c2)\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)\np3 = tf.keras.layers.MaxPooling2D((2, 2))(c3)\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)\np4 = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(c4)\n \nc5 = tf.keras.layers.Conv2D(256, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(p4)\nc5 = tf.keras.layers.Dropout(0.3)(c5)\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])\nc6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u6)\nc6 = tf.keras.layers.Dropout(0.2)(c6)\nc6 = tf.keras.layers.Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c6)\n \nu7 = tf.keras.layers.Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(c6)\nu7 = tf.keras.layers.concatenate([u7, c3])\nc7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u7)\nc7 = tf.keras.layers.Dropout(0.2)(c7)\nc7 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c7)\n \nu8 = tf.keras.layers.Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(c7)\nu8 = tf.keras.layers.concatenate([u8, c2])\nc8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u8)\nc8 = tf.keras.layers.Dropout(0.1)(c8)\nc8 = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c8)\n \nu9 = tf.keras.layers.Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(c8)\nu9 = tf.keras.layers.concatenate([u9, c1], axis=3)\nc9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(u9)\nc9 = tf.keras.layers.Dropout(0.1)(c9)\nc9 = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', kernel_initializer='he_normal', padding='same')(c9)\n \noutputs = tf.keras.layers.Conv2D(1, (1, 1), activation='sigmoid')(c9)\n \nmodel = tf.keras.Model(inputs=[inputs], outputs=[outputs])\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-13T20:55:40.760657Z","iopub.execute_input":"2022-04-13T20:55:40.760951Z","iopub.status.idle":"2022-04-13T20:55:41.118971Z","shell.execute_reply.started":"2022-04-13T20:55:40.760922Z","shell.execute_reply":"2022-04-13T20:55:41.118026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.fit(trainsetx,tainsety, batch_size=16, epochs=10)","metadata":{"execution":{"iopub.status.busy":"2022-04-13T20:57:42.240184Z","iopub.execute_input":"2022-04-13T20:57:42.240521Z","iopub.status.idle":"2022-04-13T21:03:48.362803Z","shell.execute_reply.started":"2022-04-13T20:57:42.240481Z","shell.execute_reply":"2022-04-13T21:03:48.361887Z"},"trusted":true},"execution_count":null,"outputs":[]}]}