{"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":"markdown","source":"👋 In this kernel I will go through one possible approach, a histogram based method, to estimate breast densities. The method has been presented in Wu et al. (2018) \\[1\\] (see also Karssemeijer 1998 \\[2\\]). Wu et al. implement the histogram as a baseline method to compare agaist their convolutional neural network-based method.","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\">\n<b>Tip:</b> The Breast Imaging Reporting and Data System (BI-RADS) is used to classify breast density into four categories: <b>\"A\"</b>: almost entirely fatty breast tissue, <b>\"B\"</b>: areas of dense glandular tissue and fibrous connective tissue, <b>\"C\"</b>: heterogeneously dense breast tissue with many areas of glandular tissue and fibrous connective tissue, <b>\"D\"</b>: extremely dense breast tissue.\n</div>","metadata":{}},{"cell_type":"markdown","source":"<div class=\"alert alert-block alert-success\">\n    <b>Data source:</b> Radiological Society of North America. (2022, Nov 29). RSNA Screening Mammography Breast Cancer Detection, Version 1. Retrieved 2023 Feb 9 from [https://www.kaggle.com/competitions/rsna-breast-cancer-detection/data].\n</div>","metadata":{}},{"cell_type":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport sys\nimport glob\nimport pathlib\n\nimport pandas as pd\nimport numpy as np\n\nimport pydicom\nfrom pydicom.errors import InvalidDicomError\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\nimport matplotlib.pyplot as plt\n\nimport torch","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:26:59.102236Z","iopub.execute_input":"2023-02-09T04:26:59.102728Z","iopub.status.idle":"2023-02-09T04:26:59.859863Z","shell.execute_reply.started":"2023-02-09T04:26:59.102614Z","shell.execute_reply":"2023-02-09T04:26:59.858947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Clone `breast_density_classifier` repository\n\nThe `breast_density_classifier` is published under BSD-2-Clause license which is compatible with the Apache 2.0 open source license under which this notebook has been made public.","metadata":{}},{"cell_type":"code","source":"if not os.path.isdir('/kaggle/working/breast_density_classifier'):\n    !git clone https://github.com/nyukat/breast_density_classifier.git","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:26:59.861623Z","iopub.execute_input":"2023-02-09T04:26:59.862752Z","iopub.status.idle":"2023-02-09T04:26:59.868612Z","shell.execute_reply.started":"2023-02-09T04:26:59.862713Z","shell.execute_reply":"2023-02-09T04:26:59.867558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Add path","metadata":{}},{"cell_type":"code","source":"density_classifier_loc = '/kaggle/working/breast_density_classifier'\nsys.path.append(density_classifier_loc)  # According to https://www.kaggle.com/general/135988#1985330","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:26:59.869839Z","iopub.execute_input":"2023-02-09T04:26:59.870175Z","iopub.status.idle":"2023-02-09T04:26:59.881645Z","shell.execute_reply.started":"2023-02-09T04:26:59.870144Z","shell.execute_reply":"2023-02-09T04:26:59.880564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Add `__init__.py`\n\nLet's include `__init__.py` to access the files as modules.","metadata":{}},{"cell_type":"code","source":"save_path = density_classifier_loc + '__init__.py'\nif not os.path.isfile(save_path):\n    open(save_path, 'a').close()","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:26:59.884128Z","iopub.execute_input":"2023-02-09T04:26:59.884681Z","iopub.status.idle":"2023-02-09T04:26:59.895545Z","shell.execute_reply.started":"2023-02-09T04:26:59.884646Z","shell.execute_reply":"2023-02-09T04:26:59.894129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Install dependencies\n\nIn addition to the commands below, there is also a wheel (https://www.kaggle.com/code/vslaykovsky/rsna-2022-whl) which can be used in an offline setting.","metadata":{}},{"cell_type":"code","source":"!pip install python-gdcm -q\n!pip install pylibjpeg -q","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:26:59.897261Z","iopub.execute_input":"2023-02-09T04:26:59.897654Z","iopub.status.idle":"2023-02-09T04:27:22.278065Z","shell.execute_reply.started":"2023-02-09T04:26:59.897621Z","shell.execute_reply":"2023-02-09T04:27:22.276504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read metadata","metadata":{}},{"cell_type":"code","source":"train_meta = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/train.csv\")\ntrain_meta.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.280037Z","iopub.execute_input":"2023-02-09T04:27:22.280468Z","iopub.status.idle":"2023-02-09T04:27:22.384684Z","shell.execute_reply.started":"2023-02-09T04:27:22.280422Z","shell.execute_reply":"2023-02-09T04:27:22.383773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_meta.loc[train_meta['density'] == 'C'].head()","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.386016Z","iopub.execute_input":"2023-02-09T04:27:22.386335Z","iopub.status.idle":"2023-02-09T04:27:22.412078Z","shell.execute_reply.started":"2023-02-09T04:27:22.386306Z","shell.execute_reply":"2023-02-09T04:27:22.410873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"patient_id = '10038'  # folder name, corresponds to patient_id","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.413804Z","iopub.execute_input":"2023-02-09T04:27:22.41414Z","iopub.status.idle":"2023-02-09T04:27:22.419959Z","shell.execute_reply.started":"2023-02-09T04:27:22.414109Z","shell.execute_reply":"2023-02-09T04:27:22.418761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read DICOM","metadata":{}},{"cell_type":"code","source":"dcm_loc = pathlib.Path('/kaggle/input/rsna-breast-cancer-detection/train_images/')","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.421657Z","iopub.execute_input":"2023-02-09T04:27:22.422068Z","iopub.status.idle":"2023-02-09T04:27:22.431639Z","shell.execute_reply.started":"2023-02-09T04:27:22.422021Z","shell.execute_reply":"2023-02-09T04:27:22.430527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filelist = list(dcm_loc.glob(f'{patient_id}/*.dcm'))  # manually chosen patient_id from the table above\nfilelist","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.436165Z","iopub.execute_input":"2023-02-09T04:27:22.436514Z","iopub.status.idle":"2023-02-09T04:27:22.451207Z","shell.execute_reply.started":"2023-02-09T04:27:22.436481Z","shell.execute_reply":"2023-02-09T04:27:22.45009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Source: https://www.kaggle.com/code/anttiisosalo/solt-based-image-augs-rsna-bc-detection\n\nimage_dict = {}\nfor i, file in enumerate(filelist):\n    try:\n        ds = pydicom.dcmread(str(file))\n    except InvalidDicomError:\n        print(f'Invalid DICOM file: {str(file)}')\n        continue\n    \n    # print(ds)\n    \n    if hasattr(ds, 'SOPClassUID') and not ds.SOPClassUID == '1.2.840.10008.5.1.4.1.1.1.2':\n        print(f'File has unknown SOPClassUID: {ds.SOPClassUID}')\n        continue\n    \n    if hasattr(ds, 'PresentationIntentType') and not ds.PresentationIntentType == 'FOR PROCESSING':\n        print(f'Invalid Presentation Intent Type: {ds.PresentationIntentType}')\n        continue\n\n    try:\n        arr = ds.pixel_array.copy()  # get pixel array\n    except AttributeError:\n        print(f'AttributeError: Unable to return pixel array.')\n        continue\n    except ValueError:\n        print(f'ValueError: Unable to return pixel array.')\n        continue\n\n    try:\n        out = apply_voi_lut(arr, ds)  # apply VOI LUT (default LUT) or windowing operation\n    except AttributeError:\n        print(f'AttributeError: Unable to apply VOI LUT or windowing.')\n        continue\n    \n    if hasattr(ds, 'PhotometricInterpretation') and not (ds.PhotometricInterpretation == 'MONOCHROME1' or ds.PhotometricInterpretation == 'MONOCHROME2'):\n        print(f'Unknown photometric interpretation: {ds.PhotometricInterpretation}')\n        continue\n    elif not hasattr(ds, 'PhotometricInterpretation'):\n        print(f'Missing photometric interpretation.')\n        continue\n\n    if ds.PhotometricInterpretation == 'MONOCHROME1':  # ranges from bright to dark with ascending pixel values\n        out = out.max() - out\n    elif ds.PhotometricInterpretation == 'MONOCHROME2':  # ranges from dark to bright with ascending pixel values\n        pass\n\n    height = ds.Rows\n    width = ds.Columns\n    \n    out = out.reshape((height, width))  # (height, width)\n\n    if hasattr(ds, 'ImageLaterality'):\n        laterality = ds.ImageLaterality\n    else:\n        print(f'Unknown or invalid Laterality.')\n        continue\n    \n    patient = ds.PatientID\n    \n    try:\n        view = train_meta.loc[( train_meta['patient_id'] == int(patient) ) & ( train_meta['image_id'] == int(file.stem) ), 'view'].item()\n    except ValueError:\n        print(f'ValueError: Unable to return View.')\n        continue\n\n    bitdepth = ds.BitsAllocated\n    # bitsstored = ds.BitsStored\n\n    out = out.astype(np.float64)\n    out /= out.max()\n    out *= pow(2, bitdepth) - 1\n    out = out.astype(np.uint16)\n\n    if laterality == 'R' and view == 'MLO':\n        image_dict['R-MLO'] = out\n    elif laterality == 'L' and view == 'MLO':\n        image_dict['L-MLO'] = out\n    elif laterality == 'R' and view == 'CC':\n        image_dict['R-CC'] = out\n    elif laterality == 'L' and view == 'CC':\n        image_dict['L-CC'] = out\n    \n    # study = ds.StudyInstanceUID","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:22.45301Z","iopub.execute_input":"2023-02-09T04:27:22.453467Z","iopub.status.idle":"2023-02-09T04:27:23.916711Z","shell.execute_reply.started":"2023-02-09T04:27:22.453424Z","shell.execute_reply":"2023-02-09T04:27:23.91538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_dict","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:23.918476Z","iopub.execute_input":"2023-02-09T04:27:23.918863Z","iopub.status.idle":"2023-02-09T04:27:23.929729Z","shell.execute_reply.started":"2023-02-09T04:27:23.918827Z","shell.execute_reply":"2023-02-09T04:27:23.928389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Flip 'R' side images","metadata":{}},{"cell_type":"code","source":"view_l_cc = image_dict['L-CC']\nview_r_cc = np.fliplr(image_dict['R-CC'])\nview_l_mlo = image_dict['L-MLO']\nview_r_mlo = np.fliplr(image_dict['R-MLO'])","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:23.931501Z","iopub.execute_input":"2023-02-09T04:27:23.93188Z","iopub.status.idle":"2023-02-09T04:27:23.938831Z","shell.execute_reply.started":"2023-02-09T04:27:23.931848Z","shell.execute_reply":"2023-02-09T04:27:23.937878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for standard_view in [view_r_mlo, view_l_mlo, view_r_cc, view_l_cc]:\n    fig = plt.figure(figsize=(7, 7))\n    ax = fig.add_subplot(1,1,1)\n    ax.imshow(standard_view, cmap='gray')\n    plt.show()\n    \n    unique_colors = len(np.unique(standard_view))\n    mi = np.min(standard_view)\n    ma = np.max(standard_view)\n    print(f'Unique colors: {unique_colors}; Min value: {mi}; Max value: {ma}')","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:23.940221Z","iopub.execute_input":"2023-02-09T04:27:23.940589Z","iopub.status.idle":"2023-02-09T04:27:26.478237Z","shell.execute_reply.started":"2023-02-09T04:27:23.940559Z","shell.execute_reply":"2023-02-09T04:27:26.477091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Crop images","metadata":{}},{"cell_type":"markdown","source":"Here we make use [´breast_segment´](https://github.com/olieidel/breast_segment/) script which is published under MIT license which is compatible with the Apache 2.0 open source license under which this notebook has been made public.","metadata":{}},{"cell_type":"code","source":"#%%capture\n\"\"\"\nMIT License\n\nCopyright (c) 2016 Oliver Eidel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\";","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:26.479838Z","iopub.execute_input":"2023-02-09T04:27:26.480222Z","iopub.status.idle":"2023-02-09T04:27:26.487894Z","shell.execute_reply.started":"2023-02-09T04:27:26.480186Z","shell.execute_reply":"2023-02-09T04:27:26.486456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from skimage.exposure import equalize_hist\nfrom skimage.filters.rank import median\nfrom skimage.measure import regionprops\nfrom skimage.morphology import disk\nfrom skimage.segmentation import felzenszwalb\nfrom skimage.transform import rescale, resize\n\nfrom scipy.ndimage import binary_fill_holes\n\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:26.490381Z","iopub.execute_input":"2023-02-09T04:27:26.490755Z","iopub.status.idle":"2023-02-09T04:27:27.683802Z","shell.execute_reply.started":"2023-02-09T04:27:26.490722Z","shell.execute_reply":"2023-02-09T04:27:27.682906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_crop_mask(im, scale_factor=0.25, threshold=3900, felzenzwalb_scale=0.15, flipped=True):\n    im_thres = im.copy()\n    im_thres[im_thres > threshold] = 0\n    \n    im_small = rescale(im_thres, scale_factor)\n    im_small_filt = median(im_small, disk(50))\n    \n    im_small_filt = equalize_hist(im_small_filt)\n    \n    segments = felzenszwalb(im_small_filt, scale=felzenzwalb_scale)\n    segments += 1  # to prevent labels() from ignoring segment with 0's\n    \n    props = regionprops(segments)\n    props_sorted = sorted(props, key=lambda x: x.area, reverse=True)\n    \n    bg_index = 0\n    \n    bg_region = props_sorted[bg_index]\n    minr, minc, maxr, maxc = bg_region.bbox\n    filled_mask = bg_region.filled_image\n    \n    im_small_fill = np.zeros((im_small_filt.shape[0]+2, im_small_filt.shape[1]+1), dtype=int)\n    \n    im_small_fill[minr+1:maxr+1, minc:maxc] = filled_mask\n    im_small_fill[0, :] = 1  # top\n    im_small_fill[-1, :] = 1  # bottom\n    im_small_fill[:, -1] = 1  # right\n    \n    im_small_fill = binary_fill_holes(im_small_fill)\n    im_small_mask = im_small_fill[1:-1, :-1] if flipped == True else im_small_fill[1:-1, 1:]\n    \n    shape = (im.shape[1],im.shape[0])\n    im_mask = np.array(Image.fromarray(im_small_mask).resize(shape)).astype(bool)\n    \n    im_mask = ~im_mask  # invert mask\n    \n    # determine side of breast in mask and compare\n    col_sums_split = np.array_split(np.sum(im_mask, axis=0), 2)\n    left_col_sum = np.sum(col_sums_split[0])\n    right_col_sum = np.sum(col_sums_split[1])\n\n    if left_col_sum > right_col_sum:\n        breast_side_mask = True\n    else:\n        breast_side_mask = False\n\n    if breast_side_mask != flipped:  # breast mask is not on the expected side\n        im_mask = ~im_mask\n    \n    if im_mask.ravel().sum() == 0:  # if no region is found, abort and return mask the same size as the input image\n        res = np.ones_like(im).astype(bool)\n    else:\n        minr = np.argwhere(im_mask.any(axis=1)).ravel()[0]\n        maxr = np.argwhere(im_mask.any(axis=1)).ravel()[-1]\n        minc = np.argwhere(im_mask.any(axis=0)).ravel()[0]\n        maxc = np.argwhere(im_mask.any(axis=0)).ravel()[-1]\n        res = im[minr:maxr, minc:maxc].copy()\n    \n    del im\n    del im_thres\n    del im_mask\n    \n    return res","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:27.685121Z","iopub.execute_input":"2023-02-09T04:27:27.685655Z","iopub.status.idle":"2023-02-09T04:27:27.701181Z","shell.execute_reply.started":"2023-02-09T04:27:27.685612Z","shell.execute_reply":"2023-02-09T04:27:27.699986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cropped_view_l_cc = get_crop_mask(view_l_cc, scale_factor=0.25, threshold=30000, felzenzwalb_scale=0.15, flipped=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:27.70242Z","iopub.execute_input":"2023-02-09T04:27:27.702909Z","iopub.status.idle":"2023-02-09T04:27:28.981563Z","shell.execute_reply.started":"2023-02-09T04:27:27.702862Z","shell.execute_reply":"2023-02-09T04:27:28.980203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cropped_view_r_cc = get_crop_mask(view_r_cc, scale_factor=0.25, threshold=30000, felzenzwalb_scale=0.15, flipped=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:28.983139Z","iopub.execute_input":"2023-02-09T04:27:28.983502Z","iopub.status.idle":"2023-02-09T04:27:30.528755Z","shell.execute_reply.started":"2023-02-09T04:27:28.983459Z","shell.execute_reply":"2023-02-09T04:27:30.527547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cropped_view_l_mlo = get_crop_mask(view_l_mlo, scale_factor=0.25, threshold=30000, felzenzwalb_scale=0.15, flipped=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:30.532082Z","iopub.execute_input":"2023-02-09T04:27:30.532553Z","iopub.status.idle":"2023-02-09T04:27:32.159894Z","shell.execute_reply.started":"2023-02-09T04:27:30.532513Z","shell.execute_reply":"2023-02-09T04:27:32.158526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cropped_view_r_mlo = get_crop_mask(view_r_mlo, scale_factor=0.25, threshold=30000, felzenzwalb_scale=0.15, flipped=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:32.161465Z","iopub.execute_input":"2023-02-09T04:27:32.161875Z","iopub.status.idle":"2023-02-09T04:27:33.671255Z","shell.execute_reply.started":"2023-02-09T04:27:32.161839Z","shell.execute_reply":"2023-02-09T04:27:33.670033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.nn.functional as F","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:33.672669Z","iopub.execute_input":"2023-02-09T04:27:33.673023Z","iopub.status.idle":"2023-02-09T04:27:33.678977Z","shell.execute_reply.started":"2023-02-09T04:27:33.672994Z","shell.execute_reply":"2023-02-09T04:27:33.67764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_shape = tuple(map(max, zip(*[cropped_view_l_cc.shape[:2], cropped_view_r_cc.shape[:2], cropped_view_l_mlo.shape[:2], cropped_view_r_mlo.shape[:2]])))\nnew_shape","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:33.680421Z","iopub.execute_input":"2023-02-09T04:27:33.680773Z","iopub.status.idle":"2023-02-09T04:27:33.693024Z","shell.execute_reply.started":"2023-02-09T04:27:33.680739Z","shell.execute_reply":"2023-02-09T04:27:33.692012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"padded_view_l_cc = np.pad(cropped_view_l_cc.copy(), ((0, new_shape[0] - cropped_view_l_cc.shape[0]), (0, new_shape[1] - cropped_view_l_cc.shape[1])), constant_values=0)\npadded_view_r_cc = np.pad(cropped_view_r_cc.copy(), ((0, new_shape[0] - cropped_view_r_cc.shape[0]), (0, new_shape[1] - cropped_view_r_cc.shape[1])), constant_values=0)\npadded_view_l_mlo = np.pad(cropped_view_l_mlo.copy(), ((0, new_shape[0] - cropped_view_l_mlo.shape[0]), (0, new_shape[1] - cropped_view_l_mlo.shape[1])), constant_values=0)\npadded_view_r_mlo = np.pad(cropped_view_r_mlo.copy(), ((0, new_shape[0] - cropped_view_r_mlo.shape[0]), (0, new_shape[1] - cropped_view_r_mlo.shape[1])), constant_values=0)\npadded_view_l_cc.shape, padded_view_r_cc.shape, padded_view_l_mlo.shape, padded_view_r_mlo.shape","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:33.694649Z","iopub.execute_input":"2023-02-09T04:27:33.694989Z","iopub.status.idle":"2023-02-09T04:27:33.713428Z","shell.execute_reply.started":"2023-02-09T04:27:33.694958Z","shell.execute_reply":"2023-02-09T04:27:33.712047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for standard_view in [padded_view_r_mlo, padded_view_l_mlo, padded_view_r_cc, padded_view_l_cc]:\n    fig = plt.figure(figsize=(7, 7))\n    ax = fig.add_subplot(1,1,1)\n    ax.imshow(standard_view, cmap='gray')\n    plt.show()\n    \n    unique_colors = len(np.unique(standard_view))\n    mi = np.min(standard_view)\n    ma = np.max(standard_view)\n    print(f'Unique colors: {unique_colors}; Min value: {mi}; Max value: {ma}')","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:33.714923Z","iopub.execute_input":"2023-02-09T04:27:33.715473Z","iopub.status.idle":"2023-02-09T04:27:35.062396Z","shell.execute_reply.started":"2023-02-09T04:27:33.71544Z","shell.execute_reply":"2023-02-09T04:27:35.061374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Density estimation","metadata":{}},{"cell_type":"code","source":"#%%capture\n\"\"\"\nBSD 2-Clause License\n\nCopyright (c) 2018, Nan Wu, Krzysztof J. Geras, Yiqiu Shen, Jingyi Su, \nS. Gene Kim, Eric Kim, Stacey Wolfson, Linda Moy, Kyunghyun Cho\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\";","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.063917Z","iopub.execute_input":"2023-02-09T04:27:35.064248Z","iopub.status.idle":"2023-02-09T04:27:35.069285Z","shell.execute_reply.started":"2023-02-09T04:27:35.064218Z","shell.execute_reply":"2023-02-09T04:27:35.068201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import models_torch","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.07115Z","iopub.execute_input":"2023-02-09T04:27:35.072206Z","iopub.status.idle":"2023-02-09T04:27:35.091101Z","shell.execute_reply.started":"2023-02-09T04:27:35.072092Z","shell.execute_reply":"2023-02-09T04:27:35.089767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = 'cpu'","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.09876Z","iopub.execute_input":"2023-02-09T04:27:35.099731Z","iopub.status.idle":"2023-02-09T04:27:35.104838Z","shell.execute_reply.started":"2023-02-09T04:27:35.099667Z","shell.execute_reply":"2023-02-09T04:27:35.103466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"parameters = {'bins_histogram': 50}\nmodel = models_torch.BaselineHistogramModel(num_bins=parameters['bins_histogram']).to(device)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.106891Z","iopub.execute_input":"2023-02-09T04:27:35.107772Z","iopub.status.idle":"2023-02-09T04:27:35.121621Z","shell.execute_reply.started":"2023-02-09T04:27:35.107686Z","shell.execute_reply":"2023-02-09T04:27:35.120466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = 'breast_density_classifier/saved_models/BreastDensity_BaselineHistogramModel/model.p'\nmodel.load_state_dict(torch.load(model_path))","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.12293Z","iopub.execute_input":"2023-02-09T04:27:35.123412Z","iopub.status.idle":"2023-02-09T04:27:35.133051Z","shell.execute_reply.started":"2023-02-09T04:27:35.123379Z","shell.execute_reply":"2023-02-09T04:27:35.131958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Run model","metadata":{}},{"cell_type":"code","source":"import utils","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.134509Z","iopub.execute_input":"2023-02-09T04:27:35.135045Z","iopub.status.idle":"2023-02-09T04:27:35.143239Z","shell.execute_reply.started":"2023-02-09T04:27:35.135Z","shell.execute_reply":"2023-02-09T04:27:35.142135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = torch.Tensor(utils.histogram_features_generator([padded_view_l_cc, padded_view_r_cc, padded_view_l_mlo, padded_view_r_mlo], parameters)).to(device)","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:35.144915Z","iopub.execute_input":"2023-02-09T04:27:35.145388Z","iopub.status.idle":"2023-02-09T04:27:36.330929Z","shell.execute_reply.started":"2023-02-09T04:27:35.145343Z","shell.execute_reply":"2023-02-09T04:27:36.329776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with torch.no_grad():\n    predicted_density = model(x).cpu().numpy()","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:36.332495Z","iopub.execute_input":"2023-02-09T04:27:36.332835Z","iopub.status.idle":"2023-02-09T04:27:36.358741Z","shell.execute_reply.started":"2023-02-09T04:27:36.332805Z","shell.execute_reply":"2023-02-09T04:27:36.357768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f'A: {str(predicted_density[0, 0])}; ' \\\n      f'B: {str(predicted_density[0, 1])}; ' \\\n      f'C: {str(predicted_density[0, 2])}; ' \\\n      f'D: {str(predicted_density[0, 3])}; ')","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:36.360922Z","iopub.execute_input":"2023-02-09T04:27:36.361264Z","iopub.status.idle":"2023-02-09T04:27:36.367224Z","shell.execute_reply.started":"2023-02-09T04:27:36.361232Z","shell.execute_reply":"2023-02-09T04:27:36.365992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Combine results","metadata":{}},{"cell_type":"code","source":"res = np.argmax([predicted_density[0, 0], predicted_density[0, 1], predicted_density[0, 2], predicted_density[0, 3]])","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:36.368978Z","iopub.execute_input":"2023-02-09T04:27:36.369314Z","iopub.status.idle":"2023-02-09T04:27:36.383244Z","shell.execute_reply.started":"2023-02-09T04:27:36.369282Z","shell.execute_reply":"2023-02-09T04:27:36.382055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"density_classes = list('ABCD')","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:36.384545Z","iopub.execute_input":"2023-02-09T04:27:36.385586Z","iopub.status.idle":"2023-02-09T04:27:36.396468Z","shell.execute_reply.started":"2023-02-09T04:27:36.38555Z","shell.execute_reply":"2023-02-09T04:27:36.395208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.array(density_classes)[res]","metadata":{"execution":{"iopub.status.busy":"2023-02-09T04:27:36.39831Z","iopub.execute_input":"2023-02-09T04:27:36.399183Z","iopub.status.idle":"2023-02-09T04:27:36.411609Z","shell.execute_reply.started":"2023-02-09T04:27:36.399145Z","shell.execute_reply":"2023-02-09T04:27:36.410726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The histogram based result is highly dependent on the pre-processing, **cropping** and **number of bins**. The reference class for this patient is **'C'**. It should be noted, that density assesment is somewaht subjective and can also include observer variability.","metadata":{}},{"cell_type":"markdown","source":"# Conclusions\n\nThe predicted densities, when they are tuned to match the reference densities, can be used, for example, to partition the competition data according to the breast tissue density. 👍","metadata":{}},{"cell_type":"markdown","source":"# References\n\n\\[1\\] Nan Wu, Krzysztof J. Geras, Yiqiu Shen, Jingyi Su, S. Gene Kim, Eric Kim, Stacey Wolfson, Linda Moy & Kyunghyun Cho, \"Breast density classification with deep convolutional neural networks,\" In 2018 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pp. 6682--6686, 2018. URL: https://github.com/nyukat/breast_density_classifier/\n\n\\[2\\] Nico Karssemeijer, “Automated classification of parenchymal patterns in mammograms,” Physics in Medicine & Biology, vol. 43, no. 2, pp. 365--378, 1998. DOI: 10.1088/0031-9155/43/2/011.","metadata":{}}]}