{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\n#for 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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install pydicom","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from glob import glob\nimport pydicom\nfrom matplotlib import pyplot as plt\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\nfrom tqdm import tqdm_notebook\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/rsna-str-pulmonary-embolism-detection/train.csv\")\ntest = pd.read_csv(\"../input/rsna-str-pulmonary-embolism-detection/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isna().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['filename'] = train[['StudyInstanceUID', 'SeriesInstanceUID', 'SOPInstanceUID']].apply(\n    lambda x: '/'.join(x.astype(str)),\n    axis=1\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['filename'].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import Sequence\nfrom skimage.transform import resize\nimport math\nclass generator(Sequence):\n    \n    def __init__(self,df,images_path,batch_size=32, image_size=256, shuffle=True):\n        self.df=df\n        self.images_path = images_path\n        self.batch_size = batch_size\n        self.image_size = image_size\n        self.shuffle = shuffle\n        self.nb_iteration = math.ceil((self.df.shape[0])/self.batch_size)\n        self.on_epoch_end()\n        \n    def load_img(self, filename):\n        # load dicom file as numpy array\n        img = pydicom.dcmread(filename).pixel_array\n        img= resize(img,(self.image_size, self.image_size))\n        img = img.reshape((self.image_size, self.image_size, 1))\n        np.stack([img, img, img], axis=2).reshape((self.image_size, self.image_size, 3))\n        return img\n        \n    def __getitem__(self, index):\n        # select batch\n        indicies = list(range(index*self.batch_size, min((index*self.batch_size)+self.batch_size ,(self.df.shape[0]))))\n        \n        images = []\n        for img_path in self.df['filename'].iloc[indicies].tolist():\n            img_path = img_path+\".dcm\"\n            img = self.load_img(os.path.join(self.images_path,img_path))\n            images.append(img)\n        y = self.df[['negative_exam_for_pe', 'rv_lv_ratio_gte_1', 'rv_lv_ratio_lt_1',\n                     'leftsided_pe', 'chronic_pe', 'rightsided_pe',\n                     'acute_and_chronic_pe', 'central_pe', 'indeterminate']].iloc[indicies].values\n        return np.array(images), np.array(y)\n         \n    def on_epoch_end(self):\n        if self.shuffle:\n            self.df=self.df.sample(frac=1)\n        \n    def __len__(self):\n        return self.nb_iteration","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_path=\"../input/rsna-str-pulmonary-embolism-detection/train/\"\ndf_train= train.iloc[:20000]\ndf_val= train.iloc[20000:25000]\ntrain_dataloader =  generator(df_train,images_path)\nval_dataloader =  generator(df_val,images_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x,y = next(enumerate(train_dataloader))[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inputs = Input((256, 256, 1))\nDensenet_model = tf.keras.applications.DenseNet121(\n            include_top=False,\n            weights=None,\n            input_shape=(256,256,1))\n\noutputs = Densenet_model(inputs)\noutputs = GlobalAveragePooling2D()(outputs)\noutputs = Dropout(0.25)(outputs)\noutputs = Dense(1024, activation='relu')(outputs)\noutputs = Dropout(0.25)(outputs)\noutputs = Dense(256, activation='relu')(outputs)\noutputs = Dropout(0.25)(outputs)\noutputs = Dense(64, activation='relu')(outputs)\nnepe = Dense(1, activation='sigmoid', name='negative_exam_for_pe')(outputs)\nrlrg1 = Dense(1, activation='sigmoid', name='rv_lv_ratio_gte_1')(outputs)\nrlrl1 = Dense(1, activation='sigmoid', name='rv_lv_ratio_lt_1')(outputs) \nlspe = Dense(1, activation='sigmoid', name='leftsided_pe')(outputs)\ncpe = Dense(1, activation='sigmoid', name='chronic_pe')(outputs)\nrspe = Dense(1, activation='sigmoid', name='rightsided_pe')(outputs)\naacpe = Dense(1, activation='sigmoid', name='acute_and_chronic_pe')(outputs)\ncnpe = Dense(1, activation='sigmoid', name='central_pe')(outputs)\nindt = Dense(1, activation='sigmoid', name='indeterminate')(outputs)\n\nmodel = Model(inputs=inputs, outputs={'negative_exam_for_pe':nepe,\n                                      'rv_lv_ratio_gte_1':rlrg1,\n                                      'rv_lv_ratio_lt_1':rlrl1,\n                                      'leftsided_pe':lspe,\n                                      'chronic_pe':cpe,\n                                      'rightsided_pe':rspe,\n                                      'acute_and_chronic_pe':aacpe,\n                                      'central_pe':cnpe,\n                                      'indeterminate':indt})\n\n\nmodel.compile(optimizer=Adam(lr=1e-3),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nplot_model(model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model.fit_generator( train_dataloader,validation_data = val_dataloader,epochs = 5)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}