{"cells":[{"metadata":{"trusted":true,"_uuid":"ae448b0ed29194053d40ebd29b2fa03982468552"},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pydicom\nimport pandas as pd\nfrom glob import glob\nimport os\nfrom matplotlib.patches import Rectangle\ndet_class_path = '../input/rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv'\nbbox_path = '../input/rsna-pneumonia-detection-challenge/stage_2_train_labels.csv'\ndicom_dir = '../input/rsna-pneumonia-detection-challenge/stage_2_train_images/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a0a43187041d2773c035b62f68a9687811f9fcc2"},"cell_type":"code","source":"det_class_df = pd.read_csv(det_class_path)\nprint(det_class_df.shape[0], 'class infos loaded')\nprint(det_class_df['patientId'].value_counts().shape[0], 'patient cases')\ndet_class_df.groupby('class').size().plot.bar()\ndet_class_df.sample(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cc03f5c79bee9f015c12dc8181f7997df584fbb8"},"cell_type":"code","source":"bbox_df = pd.read_csv(bbox_path)\nprint(bbox_df.shape[0], 'boxes loaded')\nprint(bbox_df['patientId'].value_counts().shape[0], 'patient cases')\nbbox_df.sample(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"91447e135cd4525c0869692ab6a6269e5bc9f30f"},"cell_type":"code","source":"comb_bbox_df = pd.concat([bbox_df, \n                        det_class_df.drop('patientId',1)], 1)\nprint(comb_bbox_df.shape[0], 'combined cases')\ncomb_bbox_df.sample(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"569f38045b0359ae0635bca97dbbe600785ff565"},"cell_type":"code","source":"box_df = comb_bbox_df.groupby('patientId').size().reset_index(name='boxes')\ncomb_box_df = pd.merge(comb_bbox_df, box_df, on='patientId')\nbox_df.\\\n    groupby('boxes').\\\n    size().\\\n    reset_index(name='patients')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2386013f7461e1407f1e782865228d146264bff0"},"cell_type":"code","source":"comb_bbox_df.groupby(['class', 'Target']).size().reset_index(name='Patient Count')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"46fe765772e24397a94295a70dbde46254c4cc8b"},"cell_type":"code","source":"image_df = pd.DataFrame({'path': glob(os.path.join(dicom_dir, '*.dcm'))})\nimage_df['patientId'] = image_df['path'].map(lambda x: os.path.splitext(os.path.basename(x))[0])\nprint(image_df.shape[0], 'images found')\nimg_pat_ids = set(image_df['patientId'].values.tolist())\nbox_pat_ids = set(comb_box_df['patientId'].values.tolist())\n\nassert img_pat_ids.union(box_pat_ids)==img_pat_ids, \"Patient IDs should be the same\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"49b1259692d6246459452f80ff2d7e1d4755d28d"},"cell_type":"code","source":"image_bbox_df = pd.merge(comb_box_df, \n                         image_df, \n                         on='patientId',\n                        how='left').sort_values('patientId')\nprint(image_bbox_df.shape[0], 'image bounding boxes')\nimage_bbox_df.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6fd8a408e2999759d3cc7500f7cb6d03d767103d"},"cell_type":"code","source":"DCM_TAG_LIST = ['PatientAge', 'BodyPartExamined', 'ViewPosition', 'PatientSex']\ndef get_tags(in_path):\n    c_dicom = pydicom.read_file(in_path, stop_before_pixels=False)\n    tag_dict = {c_tag: getattr(c_dicom, c_tag, '') \n         for c_tag in DCM_TAG_LIST}\n    tag_dict['path'] = in_path\n    return pd.Series(tag_dict)\nimage_meta_df = image_df.apply(lambda x: get_tags(x['path']), 1)\n\nimage_meta_df['PatientAge'] = image_meta_df['PatientAge'].map(int)\nimage_meta_df['PatientAge'].hist()\nimage_meta_df.drop('path',1).describe(exclude=np.number)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e42002854e4a06e6bc9ff24337b63bb42af9d2f"},"cell_type":"code","source":"image_full_df = pd.merge(image_df,\n                         image_meta_df,\n                         on='path')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5aa2c0ab7e7970ed26de93d66eb52cd4b08e57b6"},"cell_type":"code","source":"sample_df = image_bbox_df.\\\n    groupby(['Target','class', 'boxes']).\\\n    apply(lambda x: x[x['patientId']==x.sample(1)['patientId'].values[0]]).\\\n    reset_index(drop=True)\nsample_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a110097202462adb9042a02cf5ce641584717043"},"cell_type":"code","source":"fig, m_axs = plt.subplots(2, 3, figsize = (20, 10))\nfor c_ax, (c_path, c_rows) in zip(m_axs.flatten(),\n                    sample_df.groupby(['path'])):\n    c_dicom = pydicom.read_file(c_path)\n    c_ax.imshow(c_dicom.pixel_array, cmap='bone')\n    c_ax.set_title('{class}'.format(**c_rows.iloc[0,:]))\n    for i, (_, c_row) in enumerate(c_rows.dropna().iterrows()):\n        c_ax.plot(c_row['x'], c_row['y'], 's', label='{class}'.format(**c_row))\n        c_ax.add_patch(Rectangle(xy=(c_row['x'], c_row['y']),\n                                width=c_row['width'],\n                                height=c_row['height'], \n                                 alpha = 0.5))\n        if i==0: c_ax.legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a0e9bb4b310379c622055f7a18a5084795ed0e10"},"cell_type":"code","source":"pos_bbox = image_bbox_df.query('Target==1')\npos_bbox.plot.scatter(x='x', y='y')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8e5a67838560247ef72e5669cdf6369b243dc998"},"cell_type":"code","source":"fig, ax1 = plt.subplots(1, 1, figsize = (10, 10))\nax1.set_xlim(0, 1024)\nax1.set_ylim(0, 1024)\nfor _, c_row in pos_bbox.sample(1000).iterrows():\n    ax1.add_patch(Rectangle(xy=(c_row['x'], c_row['y']),\n                 width=c_row['width'],\n                 height=c_row['height'],\n                           alpha=5e-3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"99d9163a94d7991d209e984d9d2b6774fc6d8a77"},"cell_type":"code","source":"# Show the boxes themselves\nX_STEPS, Y_STEPS = 1024, 1024\nxx, yy = np.meshgrid(np.linspace(0, 1024, X_STEPS),\n           np.linspace(0, 1024, Y_STEPS), \n           indexing='xy')\nprob_image = np.zeros_like(xx)\nfor _, c_row in pos_bbox.sample(5000).iterrows():\n    c_mask = (xx>=c_row['x']) & (xx<=(c_row['x']+c_row['width']))\n    c_mask &= (yy>=c_row['y']) & (yy<=c_row['y']+c_row['height'])\n    prob_image += c_mask\nfig, ax1 = plt.subplots(1, 1, figsize = (10, 10))\nax1.imshow(prob_image, cmap='hot')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f03e4f67dbff68cedf2cc9b29ed489fe2fcdec62"},"cell_type":"code","source":"fig, m_axs = plt.subplots(2, 3, figsize = (20, 10))\nfor c_ax, (c_path, c_rows) in zip(m_axs.flatten(),\n                    sample_df.groupby(['path'])):\n    c_img_arr = pydicom.read_file(c_path).pixel_array\n    # overlay\n    c_img = plt.cm.gray(c_img_arr)\n    c_img += 0.25*plt.cm.hot(prob_image/prob_image.max())\n    c_img = np.clip(c_img, 0, 1)\n    c_ax.imshow(c_img)\n    \n    c_ax.set_title('{class}'.format(**c_rows.iloc[0,:]))\n    for i, (_, c_row) in enumerate(c_rows.dropna().iterrows()):\n        c_ax.plot(c_row['x'], c_row['y'], 's', label='{class}'.format(**c_row))\n        c_ax.add_patch(Rectangle(xy=(c_row['x'], c_row['y']),\n                                width=c_row['width'],\n                                height=c_row['height'], \n                                 alpha = 0.5,\n                                fill=False))\n        if i==0: c_ax.legend()\nfig.savefig('overview.png', figdpi = 600)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"497116383a76bd6285edf70c2604924f6e5e1687"},"cell_type":"code","source":"image_bbox_df.to_csv('image_bbox_full.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BASE_MODEL= 'VGG16' \nIMG_SIZE = (384, 384)\nBATCH_SIZE = 24\nDENSE_COUNT = 128\nDROPOUT = 0.25\nLEARN_RATE = 1e-4 \nTRAIN_SAMPLES = 8000 \nTEST_SAMPLES = 800\nUSE_ATTN = False ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder, OneHotEncoder\nclass_enc = LabelEncoder()\nimage_bbox_df['class_idx'] = class_enc.fit_transform(image_bbox_df['class'])\noh_enc = OneHotEncoder(sparse=False)\nimage_bbox_df['class_vec'] = oh_enc.fit_transform(\n    image_bbox_df['class_idx'].values.reshape(-1, 1)).tolist() \nimage_bbox_df.sample(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nimage_df = image_bbox_df.groupby('patientId').apply(lambda x: x.sample(1))\nraw_train_df, valid_df = train_test_split(image_df, test_size=0.25, random_state=2018,\n                                    stratify=image_df['class'])\nprint(raw_train_df.shape, 'training data')\nprint(valid_df.shape, 'validation data')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (20, 10))\nraw_train_df.groupby('class').size().plot.bar(ax=ax1)\ntrain_df = raw_train_df.groupby('class').\\\n    apply(lambda x: x.sample(TRAIN_SAMPLES//3)).\\\n    reset_index(drop=True)\ntrain_df.groupby('class').size().plot.bar(ax=ax2) \nprint(train_df.shape[0], 'new training size')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    # keras 2.2\n    import keras_preprocessing.image as KPImage\nexcept:\n    # keras 2.1\n    import keras.preprocessing.image as KPImage\n    \nfrom PIL import Image\nimport pydicom\ndef read_dicom_image(in_path):\n    img_arr = pydicom.read_file(in_path).pixel_array\n    return img_arr/img_arr.max()\n    \nclass medical_pil():\n    @staticmethod\n    def open(in_path):\n        if '.dcm' in in_path:\n            c_slice = read_dicom_image(in_path)\n            int_slice =  (255*c_slice).clip(0, 255).astype(np.uint8) # 8bit images are more friendly\n            return Image.fromarray(int_slice)\n        else:\n            return Image.open(in_path)\n    fromarray = Image.fromarray\nKPImage.pil_image = medical_pil","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.vgg16 import VGG16 as PTModel, preprocess_input\nimg_gen_args = dict(samplewise_center=False, \n                              samplewise_std_normalization=False, \n                              horizontal_flip = True, \n                              vertical_flip = False, \n                              height_shift_range = 0.05, \n                              width_shift_range = 0.02, \n                              rotation_range = 3, \n                              shear_range = 0.01,\n                              fill_mode = 'nearest',\n                              zoom_range = 0.05,\n                               preprocessing_function=preprocess_input)\nimg_gen = ImageDataGenerator(**img_gen_args)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def flow_from_dataframe(img_data_gen, in_df, path_col, y_col, seed = None, **dflow_args):\n    base_dir = os.path.dirname(in_df[path_col].values[0])\n    print('## Ignore next message from keras, values are replaced anyways: seed: {}'.format(seed))\n    df_gen = img_data_gen.flow_from_directory(base_dir, \n                                     class_mode = 'sparse',\n                                              seed = seed,\n                                    **dflow_args)\n    df_gen.filenames = in_df[path_col].values\n    df_gen.classes = np.stack(in_df[y_col].values,0)\n    df_gen.samples = in_df.shape[0]\n    df_gen.n = in_df.shape[0]\n    df_gen._set_index_array()\n    df_gen.directory = '' # since we have the full path\n    print('Reinserting dataframe: {} images'.format(in_df.shape[0]))\n    return df_gen","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen = flow_from_dataframe(img_gen, train_df, \n                             path_col = 'path',\n                            y_col = 'class_vec', \n                            target_size = IMG_SIZE,\n                             color_mode = 'rgb',\n                            batch_size = BATCH_SIZE)\n\nvalid_gen = flow_from_dataframe(img_gen, valid_df, \n                             path_col = 'path',\n                            y_col = 'class_vec', \n                            target_size = IMG_SIZE,\n                             color_mode = 'rgb',\n                            batch_size = 256) \n\nvalid_X, valid_Y = next(flow_from_dataframe(img_gen, \n                               valid_df, \n                             path_col = 'path',\n                            y_col = 'class_vec', \n                            target_size = IMG_SIZE,\n                             color_mode = 'rgb',\n                            batch_size = TEST_SAMPLES)) # one big batch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"t_x, t_y = next(train_gen)\nprint(t_x.shape, t_y.shape)\nfig, m_axs = plt.subplots(2, 4, figsize = (16, 8))\nfor (c_x, c_y, c_ax) in zip(t_x, t_y, m_axs.flatten()):\n    c_ax.imshow(c_x[:,:,0], cmap = 'bone')\n    c_ax.set_title('%s' % class_enc.classes_[np.argmax(c_y)])\n    c_ax.axis('off')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_pretrained_model = PTModel(input_shape =  t_x.shape[1:], \n                              include_top = False, weights = '../input/keras-pretrained-models/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5')\nbase_pretrained_model.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import GlobalAveragePooling2D, Dense, Dropout, Flatten, Input, Conv2D, multiply, LocallyConnected2D, Lambda, AvgPool2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras import layers\npt_features = Input(base_pretrained_model.get_output_shape_at(0)[1:], name = 'feature_input')\npt_depth = base_pretrained_model.get_output_shape_at(0)[-1]\nfrom keras.layers import BatchNormalization\nbn_features = BatchNormalization()(pt_features)\ngap = GlobalAveragePooling2D()(bn_features)\n\ngap_dr = Dropout(DROPOUT)(gap)\ndr_steps = Dropout(DROPOUT)(Dense(DENSE_COUNT, activation = 'linear', use_bias=False)(gap_dr))\ndr_steps = BatchNormalization()(dr_steps)\ndr_steps = layers.LeakyReLU(0.1)(dr_steps)\nout_layer = Dense(t_y.shape[1], activation = 'softmax')(dr_steps)\n\nattn_model = Model(inputs = [pt_features], \n                   outputs = [out_layer], name = 'trained_model')\n\nattn_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.optimizers import Adam\npneu_model = Sequential(name = 'combined_model')\nbase_pretrained_model.trainable = False\npneu_model.add(base_pretrained_model)\npneu_model.add(attn_model)\npneu_model.compile(optimizer = Adam(lr = LEARN_RATE), loss = 'categorical_crossentropy',\n                           metrics = ['categorical_accuracy'])\npneu_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau\nweight_path=\"{}_weights.best.hdf5\".format('lung_opacity')\n\ncheckpoint = ModelCheckpoint(weight_path, monitor='val_loss', verbose=1, \n                             save_best_only=True, mode='min', save_weights_only = True)\n\nreduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.8, \n                                   patience=10, verbose=1, mode='auto', \n                                   epsilon=0.0001, cooldown=5, min_lr=0.0001)\nearly = EarlyStopping(monitor=\"val_loss\", \n                      mode=\"min\", \n                      patience=10)\ncallbacks_list = [checkpoint, early, reduceLROnPlat]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen.batch_size = BATCH_SIZE\npneu_model.fit_generator(train_gen, \n                         steps_per_epoch=train_gen.n//BATCH_SIZE,\n                         validation_data=(valid_X, valid_Y), \n                         epochs=6, \n                         callbacks=callbacks_list,\n                         workers=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_Y = pneu_model.predict(valid_X, \n                          batch_size = BATCH_SIZE, \n                          verbose = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import classification_report, confusion_matrix\nplt.matshow(confusion_matrix(np.argmax(valid_Y, -1), np.argmax(pred_Y,-1)))\nprint(classification_report(np.argmax(valid_Y, -1), \n                            np.argmax(pred_Y,-1), target_names = class_enc.classes_))","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}