{"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":"2021-10-16T15:21:56.265687Z","iopub.execute_input":"2021-10-16T15:21:56.266088Z","iopub.status.idle":"2021-10-16T15:21:56.274235Z","shell.execute_reply.started":"2021-10-16T15:21:56.266057Z","shell.execute_reply":"2021-10-16T15:21:56.273422Z"},"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":"2021-10-16T15:21:56.276118Z","iopub.execute_input":"2021-10-16T15:21:56.276344Z","iopub.status.idle":"2021-10-16T15:22:02.207475Z","shell.execute_reply.started":"2021-10-16T15:21:56.276317Z","shell.execute_reply":"2021-10-16T15:22:02.206381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# نعمل علي فط الضغط عن الملفات \nimport zipfile\nwith zipfile.ZipFile(\"../input/data-science-bowl-2018/stage1_train.zip\",\"r\") as zip_ref:\n    zip_ref.extractall(\"stage1_train\")","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:02.208663Z","iopub.execute_input":"2021-10-16T15:22:02.208908Z","iopub.status.idle":"2021-10-16T15:22:08.517490Z","shell.execute_reply.started":"2021-10-16T15:22:02.208866Z","shell.execute_reply":"2021-10-16T15:22:08.516645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# فك الضغط ايضا \nimport zipfile\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":"2021-10-16T15:22:08.519549Z","iopub.execute_input":"2021-10-16T15:22:08.519784Z","iopub.status.idle":"2021-10-16T15:22:08.787715Z","shell.execute_reply.started":"2021-10-16T15:22:08.519755Z","shell.execute_reply":"2021-10-16T15:22:08.786891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# البذور العشوائيه هي اداه هامه في تثبيت النتائج التي تعتمد علي الاختيار العشوائي \nseed = 42\nnp.random.seed = seed","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:43:52.871362Z","iopub.execute_input":"2021-10-16T15:43:52.871655Z","iopub.status.idle":"2021-10-16T15:43:52.876118Z","shell.execute_reply.started":"2021-10-16T15:43:52.871624Z","shell.execute_reply":"2021-10-16T15:43:52.875103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_WIDTH = 128\nIMG_HEIGHT = 128\nIMG_CHANNELS = 3\n\nTRAIN_PATH = 'stage1_train/'\nTEST_PATH = 'stage1_test/'\n\n# تلك التعليمه تعمل علي \n# اظهار اسم الملف الاول وجميع الملفات التي يحتويها , ونحن نريد الملفات التي يحتويها وتجاهل الملف الرئيسي \n# لذلك نعمل علي اضافه رقم 1 الي الكود وتعني العنصر الثاني .\n#train_ids = next(os.walk(TRAIN_PATH))\n\ntrain_ids = next(os.walk(TRAIN_PATH))[1]\n# ستتكرر نفس العمليه مع بيانات الاختبار \ntest_ids = next(os.walk(TEST_PATH))[1]\n\n\n# هنا نعمل علي اضافه سلاسل فارغه نعمل علي تخزين النتائج التي نحصل عليها فيما بعد \n# الهدف هنا هو استخراج كل الصور واعاده تشكليها \nX_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nY_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.bool)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:08.788808Z","iopub.execute_input":"2021-10-16T15:22:08.789092Z","iopub.status.idle":"2021-10-16T15:22:08.797483Z","shell.execute_reply.started":"2021-10-16T15:22:08.789051Z","shell.execute_reply":"2021-10-16T15:22:08.796767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ids[:5]","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:08.798623Z","iopub.execute_input":"2021-10-16T15:22:08.798841Z","iopub.status.idle":"2021-10-16T15:22:08.810550Z","shell.execute_reply.started":"2021-10-16T15:22:08.798817Z","shell.execute_reply":"2021-10-16T15:22:08.809673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ids[:5]","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:08.811950Z","iopub.execute_input":"2021-10-16T15:22:08.812490Z","iopub.status.idle":"2021-10-16T15:22:08.823134Z","shell.execute_reply.started":"2021-10-16T15:22:08.812438Z","shell.execute_reply":"2021-10-16T15:22:08.822346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(Y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:08.824587Z","iopub.execute_input":"2021-10-16T15:22:08.825482Z","iopub.status.idle":"2021-10-16T15:22:08.833877Z","shell.execute_reply.started":"2021-10-16T15:22:08.825428Z","shell.execute_reply":"2021-10-16T15:22:08.833028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هنا نعمل علي طباعه جمله افتتاحيه في البدايه \nprint('Resizing training images and masks')\n# هنا نقوم بانشاء لوب \n# تلك الداله tqdm \n# تعمل علي اظهار شريط التقدم \nfor n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)):  \n    # الان اصبح لدينا مسار يدخل الي /او  يتخطي الملف الاول ويدخل الي الملفين \n    path = TRAIN_PATH + id_\n    # هنا نقوم بدمج المسار مع اسم من اسماء الملفات الموجوده في الملف الثاني حتي يستطيع الدخول اليها وتحويل نوع الصور التي يبدا في تكاراها الي نوع موحد من امتدادات الصور \n    img = imread(path + '/images/' + id_ + '.png')[:,:,:IMG_CHANNELS]  \n    # بعدها يعمل علي اعاده تشكيل حجم الصوره الي الابعاد التي اشرنا اليها مسبقا \n    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n    # بعدها مباشره نعمل علي تخزين تلك الصوره الناتجه داخل المصفوفه التي قمنا بانشاءها \n    X_train[n] = img  #Fill empty X_train with values from img\n    mask = np.zeros((IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.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_train[n] = mask  ","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:22:08.834954Z","iopub.execute_input":"2021-10-16T15:22:08.835655Z","iopub.status.idle":"2021-10-16T15:29:30.130246Z","shell.execute_reply.started":"2021-10-16T15:22:08.835608Z","shell.execute_reply":"2021-10-16T15:29:30.129407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(path)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:30.133063Z","iopub.execute_input":"2021-10-16T15:29:30.133845Z","iopub.status.idle":"2021-10-16T15:29:30.138724Z","shell.execute_reply.started":"2021-10-16T15:29:30.133797Z","shell.execute_reply":"2021-10-16T15:29:30.137929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هذا هو بعد  الصوره بعد اجراء تحجيم لها \nprint(img.shape)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:30.140011Z","iopub.execute_input":"2021-10-16T15:29:30.140859Z","iopub.status.idle":"2021-10-16T15:29:30.151586Z","shell.execute_reply.started":"2021-10-16T15:29:30.140814Z","shell.execute_reply":"2021-10-16T15:29:30.150843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هذا هو المخزن الذي يحتوي علي كل الصور التي ليدنا بنفس الابعاد \nprint(X_train.shape)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:30.152946Z","iopub.execute_input":"2021-10-16T15:29:30.153786Z","iopub.status.idle":"2021-10-16T15:29:30.161665Z","shell.execute_reply.started":"2021-10-16T15:29:30.153742Z","shell.execute_reply":"2021-10-16T15:29:30.160847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test images\nX_test = 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    X_test[n] = img\n\nprint('Done!')","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:30.163030Z","iopub.execute_input":"2021-10-16T15:29:30.164013Z","iopub.status.idle":"2021-10-16T15:29:32.229353Z","shell.execute_reply.started":"2021-10-16T15:29:30.163819Z","shell.execute_reply":"2021-10-16T15:29:32.228299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test.shape","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:32.230837Z","iopub.execute_input":"2021-10-16T15:29:32.231169Z","iopub.status.idle":"2021-10-16T15:29:32.239084Z","shell.execute_reply.started":"2021-10-16T15:29:32.231121Z","shell.execute_reply":"2021-10-16T15:29:32.238250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img.shape","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:29:32.240779Z","iopub.execute_input":"2021-10-16T15:29:32.242094Z","iopub.status.idle":"2021-10-16T15:29:32.252712Z","shell.execute_reply.started":"2021-10-16T15:29:32.242039Z","shell.execute_reply":"2021-10-16T15:29:32.251906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هنا قمنا بانشاء رقم عشوائي يتدرج من 0 الي 670 \nimage_x = random.randint(0, len(train_ids))\n# قمنا بتمرير ذلك الرقم العشوائي \nimshow(X_train[image_x])\nplt.show()\n# هنا قمنا بتمرير نفس الرقم الي صور الماسك \nimshow(np.squeeze(Y_train[image_x]))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:43:00.470944Z","iopub.execute_input":"2021-10-16T15:43:00.472058Z","iopub.status.idle":"2021-10-16T15:43:00.977446Z","shell.execute_reply.started":"2021-10-16T15:43:00.471985Z","shell.execute_reply":"2021-10-16T15:43:00.976475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هنا هيكل الموديل الذي لدينا \n#Build the model\ninputs = tf.keras.layers.Input((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS))\ns = tf.keras.layers.Lambda(lambda x: x / 255)(inputs)\n\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":"2021-10-16T15:44:57.732585Z","iopub.execute_input":"2021-10-16T15:44:57.732894Z","iopub.status.idle":"2021-10-16T15:44:58.067330Z","shell.execute_reply.started":"2021-10-16T15:44:57.732845Z","shell.execute_reply":"2021-10-16T15:44:58.066512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Modelcheckpoint\ncheckpointer = tf.keras.callbacks.ModelCheckpoint('model_for_nuclei.h5', verbose=1, save_best_only=True)\n\ncallbacks = [\n        tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),\n        tf.keras.callbacks.TensorBoard(log_dir='logs')]\n\nresults = model.fit(X_train, Y_train, validation_split=0.1, batch_size=16, epochs=5, callbacks=callbacks)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:46:18.992758Z","iopub.execute_input":"2021-10-16T15:46:18.993079Z","iopub.status.idle":"2021-10-16T15:49:05.077855Z","shell.execute_reply.started":"2021-10-16T15:46:18.993043Z","shell.execute_reply":"2021-10-16T15:49:05.077219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"idx = random.randint(0, len(X_train))\n\n\npreds_train = model.predict(X_train[:int(X_train.shape[0]*0.9)], verbose=1)\npreds_val = model.predict(X_train[int(X_train.shape[0]*0.9):], verbose=1)\npreds_test = model.predict(X_test, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:49:33.077785Z","iopub.execute_input":"2021-10-16T15:49:33.078681Z","iopub.status.idle":"2021-10-16T15:49:43.578635Z","shell.execute_reply.started":"2021-10-16T15:49:33.078642Z","shell.execute_reply":"2021-10-16T15:49:43.577850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds_test.shape","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:50:26.536805Z","iopub.execute_input":"2021-10-16T15:50:26.537598Z","iopub.status.idle":"2021-10-16T15:50:26.542802Z","shell.execute_reply.started":"2021-10-16T15:50:26.537551Z","shell.execute_reply":"2021-10-16T15:50:26.541914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds_train_t = (preds_train > 0.5).astype(np.uint8)\npreds_val_t = (preds_val > 0.5).astype(np.uint8)\npreds_test_t = (preds_test > 0.5).astype(np.uint8)","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:55:06.087221Z","iopub.execute_input":"2021-10-16T15:55:06.087557Z","iopub.status.idle":"2021-10-16T15:55:06.106301Z","shell.execute_reply.started":"2021-10-16T15:55:06.087523Z","shell.execute_reply":"2021-10-16T15:55:06.105520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# هنا نتاكد من ان ننتائج التدريب جيده \n# Perform a sanity check on some random training samples\nix = random.randint(0, len(preds_train_t))\nimshow(X_train[ix])\nplt.show()\nimshow(np.squeeze(Y_train[ix]))\nplt.show()\nimshow(np.squeeze(preds_train_t[ix]))\nplt.show()\n\n# Perform a sanity check on some random validation samples\nix = random.randint(0, len(preds_val_t))\nimshow(X_train[int(X_train.shape[0]*0.9):][ix])\nplt.show()\nimshow(np.squeeze(Y_train[int(Y_train.shape[0]*0.9):][ix]))\nplt.show()\nimshow(np.squeeze(preds_val_t[ix]))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-10-16T15:55:17.156094Z","iopub.execute_input":"2021-10-16T15:55:17.156372Z","iopub.status.idle":"2021-10-16T15:55:18.856517Z","shell.execute_reply.started":"2021-10-16T15:55:17.156342Z","shell.execute_reply":"2021-10-16T15:55:18.855661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# work in progress.......","metadata":{}},{"cell_type":"markdown","source":"# Thanks a lot: \n[https://github.com/bnsreenu/python_for_microscopists/blob/master/076-077-078-Unet_nuclei_tutorial.py](http://)","metadata":{}},{"cell_type":"markdown","source":"# هذا الموديل سيء عندما يتعلق الامر بالبيانات القليله .\n# كما انه يستغرق الكثير من الوقت في التعلم ان كانت البيانات كبيره .","metadata":{}}]}