{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install -U pylibjpeg pylibjpeg-openjpeg pylibjpeg-libjpeg","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport sys\nimport platform\nfrom PIL import Image\nimport numpy as np\nimport pydicom \nimport os\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport sys\nimport platform\nfrom PIL import Image\nimport numpy as np\nimport pydicom\nfrom tqdm.notebook import tqdm\nfrom pathlib import Path\nfrom sklearn.preprocessing import MinMaxScaler\nfrom skimage.transform import rotate, AffineTransform, warp\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport albumentations as A\nfrom sklearn.preprocessing import MinMaxScaler","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:20:36.088133Z","iopub.execute_input":"2023-03-18T13:20:36.088565Z","iopub.status.idle":"2023-03-18T13:20:36.098494Z","shell.execute_reply.started":"2023-03-18T13:20:36.088533Z","shell.execute_reply":"2023-03-18T13:20:36.097251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/train.csv\")\npath = \"/kaggle/input/rsna-breast-cancer-detection/train_images\"\ndata['file'] = data.apply(lambda x: f'{path}/{x[\"patient_id\"]}/{x[\"image_id\"]}.dcm', axis=1)\n\n\ncase = 00000\ninfo = []\n\nfor i , row in data.iterrows():\n  if not row[\"patient_id\"] == case:\n    df = data[data[\"patient_id\"] == case]\n    if len(df) == 4:\n      if (len(df.laterality.unique() == 2)) and (len(df.view.unique() == 2)):\n        imgcc_left = df[(df[\"view\"] == \"CC\") & (df[\"laterality\"]==\"L\")][\"file\"].iloc[0]\n        imgcc_right = df[(df[\"view\"] == \"CC\") & (df[\"laterality\"]==\"R\")][\"file\"].iloc[0]\n        imgmlo_left = df[(df[\"view\"] == \"MLO\") & (df[\"laterality\"]==\"L\")][\"file\"].iloc[0]\n        imgmlo_right = df[(df[\"view\"] == \"MLO\") & (df[\"laterality\"]==\"R\")][\"file\"].iloc[0]\n        \n        info.append((case , imgcc_left , imgmlo_left , df[df[\"laterality\"] == \"L\"][\"cancer\"].iloc[0] , df[df[\"laterality\"] == \"L\"][\"density\"].iloc[0]))\n        info.append((case , imgcc_right, imgmlo_right , df[df[\"laterality\"] == \"R\"][\"cancer\"].iloc[0] ,df[df[\"laterality\"] == \"R\"][\"density\"].iloc[0]))\n  case = row[\"patient_id\"]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:10:02.530876Z","iopub.execute_input":"2023-03-18T13:10:02.531531Z","iopub.status.idle":"2023-03-18T13:10:52.727826Z","shell.execute_reply.started":"2023-03-18T13:10:02.531494Z","shell.execute_reply":"2023-03-18T13:10:52.726799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info[1]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:12:24.174588Z","iopub.execute_input":"2023-03-18T13:12:24.174975Z","iopub.status.idle":"2023-03-18T13:12:24.182348Z","shell.execute_reply.started":"2023-03-18T13:12:24.174943Z","shell.execute_reply":"2023-03-18T13:12:24.181218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info_density[10]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T15:05:22.460852Z","iopub.execute_input":"2023-03-18T15:05:22.461295Z","iopub.status.idle":"2023-03-18T15:05:22.469514Z","shell.execute_reply.started":"2023-03-18T15:05:22.461259Z","shell.execute_reply":"2023-03-18T15:05:22.468236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info_density[:2]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T14:52:05.002928Z","iopub.execute_input":"2023-03-18T14:52:05.00336Z","iopub.status.idle":"2023-03-18T14:52:05.011208Z","shell.execute_reply.started":"2023-03-18T14:52:05.003325Z","shell.execute_reply":"2023-03-18T14:52:05.010121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.iloc[0][\"file\"]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T15:05:14.559542Z","iopub.execute_input":"2023-03-18T15:05:14.560385Z","iopub.status.idle":"2023-03-18T15:05:14.586865Z","shell.execute_reply.started":"2023-03-18T15:05:14.560346Z","shell.execute_reply":"2023-03-18T15:05:14.585103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = dicom_file_to_ary(\"/kaggle/input/rsna-breast-cancer-detection/train_images/10006/462822612.dcm\")","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:30:10.992493Z","iopub.execute_input":"2023-03-18T13:30:10.99286Z","iopub.status.idle":"2023-03-18T13:30:12.384014Z","shell.execute_reply.started":"2023-03-18T13:30:10.992828Z","shell.execute_reply":"2023-03-18T13:30:12.382966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img.min() , img.max()  , img.shape","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:30:14.964744Z","iopub.execute_input":"2023-03-18T13:30:14.965213Z","iopub.status.idle":"2023-03-18T13:30:15.03009Z","shell.execute_reply.started":"2023-03-18T13:30:14.965148Z","shell.execute_reply":"2023-03-18T13:30:15.029057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dicom = pydicom.read_file(\"/kaggle/input/rsna-breast-cancer-detection/train_images/10006/462822612.dcm\")\ndata = dicom.pixel_array\nif dicom.PhotometricInterpretation == \"MONOCHROME1\":\n    data = np.amax(data) - data","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:26:17.898999Z","iopub.execute_input":"2023-03-18T13:26:17.899369Z","iopub.status.idle":"2023-03-18T13:26:19.256079Z","shell.execute_reply.started":"2023-03-18T13:26:17.899338Z","shell.execute_reply":"2023-03-18T13:26:19.255057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img.min() , img.max()","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:30:35.146941Z","iopub.execute_input":"2023-03-18T13:30:35.147323Z","iopub.status.idle":"2023-03-18T13:30:35.199625Z","shell.execute_reply.started":"2023-03-18T13:30:35.147291Z","shell.execute_reply":"2023-03-18T13:30:35.198572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = scaler.fit_transform(data)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:27:20.59844Z","iopub.execute_input":"2023-03-18T13:27:20.598826Z","iopub.status.idle":"2023-03-18T13:27:20.869183Z","shell.execute_reply.started":"2023-03-18T13:27:20.598795Z","shell.execute_reply":"2023-03-18T13:27:20.868149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data*255","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:27:49.415397Z","iopub.execute_input":"2023-03-18T13:27:49.415868Z","iopub.status.idle":"2023-03-18T13:27:49.492742Z","shell.execute_reply.started":"2023-03-18T13:27:49.415828Z","shell.execute_reply":"2023-03-18T13:27:49.491672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:28:39.386228Z","iopub.execute_input":"2023-03-18T13:28:39.386598Z","iopub.status.idle":"2023-03-18T13:28:40.406057Z","shell.execute_reply.started":"2023-03-18T13:28:39.386568Z","shell.execute_reply":"2023-03-18T13:28:40.405123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:30:49.240985Z","iopub.execute_input":"2023-03-18T13:30:49.241373Z","iopub.status.idle":"2023-03-18T13:30:50.492836Z","shell.execute_reply.started":"2023-03-18T13:30:49.24134Z","shell.execute_reply":"2023-03-18T13:30:50.48824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(info)\ninfo_density =  [(c,cc,mlo,l,d) for (c,cc,mlo,l,d) in info if d in [\"A\",\"B\",\"C\",\"D\"]]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:11:40.021661Z","iopub.execute_input":"2023-03-18T13:11:40.022042Z","iopub.status.idle":"2023-03-18T13:11:40.037482Z","shell.execute_reply.started":"2023-03-18T13:11:40.02201Z","shell.execute_reply":"2023-03-18T13:11:40.036435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"scaler = MinMaxScaler()","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:29:36.115407Z","iopub.execute_input":"2023-03-18T13:29:36.115852Z","iopub.status.idle":"2023-03-18T13:29:36.124931Z","shell.execute_reply.started":"2023-03-18T13:29:36.115814Z","shell.execute_reply":"2023-03-18T13:29:36.123368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dicom_file_to_ary(path):\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\n    if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n    data = scaler.fit_transform(data)\n    data = (data * 255).astype(np.uint8)\n    return data\n\ndef add_pad(image, new_height=512, new_width=512):\n    height, width = image.shape\n\n    final_image = np.zeros((new_height, new_width))\n\n    pad_left = int((new_width - width) // 2)\n    pad_top = int((new_height - height) // 2)\n    \n    \n    # Replace the pixels with the image's pixels\n    final_image[pad_top:pad_top + height, pad_left:pad_left + width] = image\n    \n    return final_image\n\n\ndef combine2channelPad(cc,mlo):\n    if cc.shape[0] > mlo.shape[0]:\n        h = cc.shape[0]\n    else:\n        h = mlo.shape[0]\n        \n    if cc.shape[1] > mlo.shape[1]:\n        w = cc.shape[1]\n    else:\n        w = mlo.shape[1]\n        \n    \n    ccn = add_pad(cc,h,w)\n    mlon = add_pad(mlo,h,w)\n    \n    return (ccn,mlon)\n\n\n\ndef fit_image(X):\n \n    output= cv2.connectedComponentsWithStats((X > 10).astype(np.uint8)[:, :], 8, cv2.CV_32S)\n    stats = output[2]\n    idx = stats[1:, 4].argmax() + 1\n    x1, y1, w, h = stats[idx][:4]\n    x2 = x1 + w\n    y2 = y1 + h\n    X_fit = X[y1: y2, x1: x2]\n    return X_fit / 255\n\n\n\ndef sample(file):\n    a , b , c, d =  0,0,0,0\n    for _, den in file:\n        if den == \"A\":\n            a+=1\n        if den == \"B\":\n            b+=1\n        if den == \"C\":\n            c+=1\n        if den == \"D\":\n            d+=1\n        \n    return a ,b ,c ,d\n\n\n\ndef sampleb(file):\n    a , b , c, d =  0,0,0,0\n    for _,_,_,_,den in file:\n        if den == \"A\":\n            a+=1\n        if den == \"B\":\n            b+=1\n        if den == \"C\":\n            c+=1\n        if den == \"D\":\n            d+=1\n        \n    return a ,b ,c ,d\n","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:29:55.979737Z","iopub.execute_input":"2023-03-18T13:29:55.980113Z","iopub.status.idle":"2023-03-18T13:29:55.996046Z","shell.execute_reply.started":"2023-03-18T13:29:55.98008Z","shell.execute_reply":"2023-03-18T13:29:55.994792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(train_bal)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:32:09.442008Z","iopub.execute_input":"2023-03-18T13:32:09.44268Z","iopub.status.idle":"2023-03-18T13:32:09.447479Z","shell.execute_reply.started":"2023-03-18T13:32:09.442641Z","shell.execute_reply":"2023-03-18T13:32:09.446438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_bal[0]","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:32:15.553133Z","iopub.execute_input":"2023-03-18T13:32:15.553834Z","iopub.status.idle":"2023-03-18T13:32:15.560682Z","shell.execute_reply.started":"2023-03-18T13:32:15.553797Z","shell.execute_reply":"2023-03-18T13:32:15.55966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sampleb(train_bal), sampleb(info_density)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:14:26.312014Z","iopub.execute_input":"2023-03-18T13:14:26.312388Z","iopub.status.idle":"2023-03-18T13:14:26.322281Z","shell.execute_reply.started":"2023-03-18T13:14:26.312356Z","shell.execute_reply":"2023-03-18T13:14:26.321152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = train_bal[:1500]\nval = train_bal[1500:]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train_bal)","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:13:03.240124Z","iopub.execute_input":"2023-03-18T13:13:03.241275Z","iopub.status.idle":"2023-03-18T13:13:03.249184Z","shell.execute_reply.started":"2023-03-18T13:13:03.241212Z","shell.execute_reply":"2023-03-18T13:13:03.247921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_bal[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SAVE_PATH = Path(\"Processed_bal/\")\nfor c , (case , cc , mlo , can , density) in enumerate(tqdm(train_bal)):\n    \n    \n    a_cc = dicom_file_to_ary(cc)\n    a_mlo = dicom_file_to_ary(mlo)\n    \n    \n    img1=fit_image(a_cc)\n    img2=fit_image(a_mlo)\n\n                           \n    img1 , img2 = combine2channelPad(img1,img2)\n    \n    img=np.stack([img1,img2],axis=2)\n                \n    img = cv2.resize(img,(400,600),interpolation=cv2.INTER_LINEAR).astype(np.float16)\n    #img2 = cv2.resize(img2,(400,400),interpolation=cv2.INTER_LINEAR).astype(np.float16)\n    \n    \n    train_or_val = \"train\" if c < 2500 else \"val\" \n        \n    current_save_path = SAVE_PATH/train_or_val # Define save path and create if necessary\n    current_save_path.mkdir(parents=True, exist_ok=True)\n    case = str(case) + \"_\" + str(c) + \"_\" +density\n    np.save(current_save_path/case, img)  # Save the array in the corresponding directory","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:32:32.202448Z","iopub.execute_input":"2023-03-18T13:32:32.202934Z","iopub.status.idle":"2023-03-18T14:44:09.04046Z","shell.execute_reply.started":"2023-03-18T13:32:32.202889Z","shell.execute_reply":"2023-03-18T14:44:09.039102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(os.listdir(\"/kaggle/working/Processed_bal/train\"))","metadata":{"execution":{"iopub.status.busy":"2023-03-18T15:06:54.048648Z","iopub.execute_input":"2023-03-18T15:06:54.04904Z","iopub.status.idle":"2023-03-18T15:06:54.057744Z","shell.execute_reply.started":"2023-03-18T15:06:54.049007Z","shell.execute_reply":"2023-03-18T15:06:54.056565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info = {}\nfor i , row in tqdm(data.iterrows()):\n    c = row[\"patient_id\"]\n    d = row[\"density\"]\n    \n    info[c] = d","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = []\nval = []\n\nfor i , case in enumerate(os.listdir(\"/kaggle/working/Processed_bal/train\")):\n    d = info[int(case.split(\"_\")[0])]\n    train.append((case,d))\n    \nfor i , case in enumerate(os.listdir(\"/kaggle/working/Processed_bal/val\")):\n    d = info[int(case.split(\"_\")[0])]\n    val.append((case,d))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = []\n\nfor i , case in enumerate(os.listdir(\"/kaggle/working/Processed_bal/train\")):\n    d = info[int(case.split(\"_\")[0])]\n    train.append((case,d))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample(train1) ,sample(val)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1 = train[:1500]\nval = train[1500:]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_bal = []\nb = 0 \nc = 0\nfor case,cc,mlo,cancer,den in info_density:\n    if den == \"A\":\n        train_bal.append((case,cc,mlo,cancer,den))\n    if den == \"B\" and b < 750:\n        train_bal.append((case,cc,mlo,cancer,den))\n        b+=1\n    if den == \"C\" and c < 750:\n        train_bal.append((case,cc,mlo,cancer,den))\n        c+=1\n    if den == \"D\":\n        train_bal.append((case,cc,mlo,cancer,den))","metadata":{"execution":{"iopub.status.busy":"2023-03-18T13:12:49.854101Z","iopub.execute_input":"2023-03-18T13:12:49.854841Z","iopub.status.idle":"2023-03-18T13:12:49.866674Z","shell.execute_reply.started":"2023-03-18T13:12:49.854803Z","shell.execute_reply":"2023-03-18T13:12:49.865577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"d = train+val","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1 = train[:1250]\nval= train[1250:]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.shuffle(train1)\nnp.random.shuffle(val)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample(val) , sample(train1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = A.Compose([\n    A.HorizontalFlip(p=0.5),\n    A.ShiftScaleRotate(shift_limit = 0 , rotate_limit = 0 , p=0.5 ,border_mode = cv2.BORDER_CONSTANT),\n    A.CLAHE(p=1.0)\n])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img=transform(image=(imgs[0,:,:,0]*255).astype(np.uint8))[\"image\"]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(imgs[3,:,:,1],cmap=\"bone\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(img,cmap=\"bone\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(transform(image=imgs[9])[\"image\"][:,:,0],cmap=\"bone\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = A.Compose([\n    A.HorizontalFlip(p=0.7),\n    A.ShiftScaleRotate(shift_limit = 0 , rotate_limit = 0 , p=0.5 ,border_mode = cv2.BORDER_CONSTANT),\n    A.CLAHE(p=1.0)\n])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform_val = A.Compose([\n    A.CLAHE(p=1.0)\n])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_img1(img_list,tv=None,aug=None,aug_val = None):\n    img11 = []\n    img22 = []\n    label = []\n    density = []\n\n    for (case,d) in img_list:\n        \n        \n        #a_cc = dicom_file_to_ary(cc)\n        #a_mlo = dicom_file_to_ary(mlo)\n    \n    \n        #img1=fit_image(a_cc)\n        #img2=fit_image(a_mlo)\n\n                           \n        #img1 , img2 = combine2channelPad(img1,img2)\n    \n        #img=np.stack([img1,img2],axis=2)\n                \n        #img = cv2.resize(img,(400,600),interpolation=cv2.INTER_LINEAR).astype(np.float32)\n    \n        path = \"/kaggle/working/Processed_bal/\"+tv+\"/\"+case\n        img = (np.load(path)*255).astype(np.uint8)\n        \n        if aug:\n            trans = transform(image=img[:,:,0], mask =img[:,:,1])\n            img1 = trans[\"image\"]\n            img2 = trans[\"mask\"]\n            img = np.stack([img1,img2],axis = 2)\n            \n        if aug_val:\n            trans1 = transform_val(image=img[:,:,0], mask =img[:,:,1])\n            img1 = trans1[\"image\"]\n            img2 = trans1[\"mask\"]\n            img = np.stack([img1,img2],axis = 2)\n            \n            \n    \n        #img11.append(np.expand_dims(img[:,:,0],axis=2))\n        img11.append((np.expand_dims(img[:,:,0],axis=2)/255).astype(np.float32))\n\n    \n        \n        if d == \"A\":\n            density.append([1,0,0,0])\n        if d == \"B\":\n            density.append([0,1,0,0])\n        if d == \"C\":\n            density.append([0,0,1,0])\n        if d == \"D\":\n            density.append([0,0,0,1])\n\n\n    \n    img11 = np.array(img11)\n    #img22 = np.array(img22)\n    #label = np.expand_dims(np.array(label),1)\n    #label = np.array(label)\n\n    density = np.array(density)\n\n    return (img11 ,density)\n\n\ndef trainLoaderCM(batch_size):\n    L = len(train1)\n    #train2_bal = train_bal + train_bal\n    \n    while True:\n        bs = 0\n        be = batch_size\n\n        while bs < L:\n            limit = min(be , L)\n\n            img,d= load_img1(train1[bs:limit],\"train\",aug=True)\n            \n            #img = transform(image=img)['image']\n            #img=np.stack([img1,img2],axis=3)\n            #img = np.dstack((img1,img2))\n            \n            #c = np.random.randint(0,16,4)\n            \n            #ang = np.random.randint(-2,4)*10\n            #x = []\n            #for i,im in enumerate(img):\n             #   if i in c:\n              #      ang = np.random.randint(-2,3)*10\n               #     p = rotate(im,angle=ang)\n                #    x.append(p.astype(np.float16))\n                #else:\n                 #   x.append(im)\n                    \n            #imgg = np.array(x)\n\n            yield (img,d)\n\n            bs += batch_size\n            be += batch_size\n            \n            \n            \ndef valLoaderCM(batch_size):\n    L = len(val)\n\n    while True:\n        bs = 0\n        be = batch_size\n\n        while bs < L:\n            limit = min(be , L)\n\n            img,d= load_img1(val[bs:limit],\"train\",aug_val=True)\n\n            #img=np.stack([img1,img2],axis=3)\n            #img = np.dstack((img1,img2))\n\n            yield (img,d)\n\n            bs += batch_size\n            be += batch_size","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 16\ntrainloader = trainLoaderCM(batch_size)\nvalloader = valLoaderCM(batch_size)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgs , label = trainloader.__next__()\nimgsv , labelv = valloader.__next__()\nimgs.shape ,label.shape , imgs.min() , imgs.max() , imgs.dtype","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgsv.shape ,labelv.shape , imgsv.min() , imgsv.max() , imgsv.dtype","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Model ,Sequential","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel=Sequential()\n\n\nmodel.add(tf.keras.layers.RandomFlip(\n    mode=\"horizontal\", seed=None\n))\n\nmodel.add(tf.keras.layers.RandomZoom(\n    height_factor=(-0.2, -0.1),\n    width_factor=None,\n    fill_mode=\"constant\",\n    interpolation=\"bilinear\",\n    seed=None,\n    fill_value=0.0\n))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = model(imgs).numpy()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(imgs[0,:,:,0],cmap=\"bone\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 16\nimport pandas as pd\nimport numpy as np\nfrom skimage.io import imread\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\n\nfrom tensorflow.keras.layers import Input, Dense, Flatten, Dropout, Conv2D,MaxPool2D, MaxPooling2D, Activation, concatenate , LeakyReLU ,ReLU ,BatchNormalization\nfrom tensorflow.keras.models import Model ,Sequential\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.applications import ResNet50 , VGG19\nfrom tensorflow.keras.optimizers import Adam , SGD\nfrom tensorflow.keras.preprocessing.image import load_img , img_to_array\nfrom sklearn.metrics import *\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\n\nfrom tensorflow.keras import losses\n\nfrom tensorflow.keras import layers","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def lossOrdinal(y_true, y_pred):\n    weights = K.cast(K.abs(K.argmax(y_true, axis=1) - K.argmax(y_pred, axis=1))/(4 - 1), dtype='float32')\n    return (1.0 + weights) * losses.categorical_crossentropy(y_true, y_pred)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg_model = VGG19(include_top=False, weights='imagenet')\nvgg_config = vgg_model.get_config()\nh, w, c = 600,400,1\nvgg_config[\"layers\"][0][\"config\"][\"batch_input_shape\"] = (None, h, w, c)\nvgg_updated = Model.from_config(vgg_config)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def avg_and_copy_wts(weights, num_channels_to_fill):  #num_channels_to_fill are the extra channels for which we need to fill weights\n  average_weights = np.mean(weights, axis=-2).reshape(weights[:,:,-1:,:].shape)  #Find mean along the channel axis (second to last axis)\n  wts_copied_to_mult_channels = np.tile(average_weights, (num_channels_to_fill, 1)) #Repeat (copy) the array multiple times\n  return(wts_copied_to_mult_channels)\n\ndef avg_wts(weights):  \n  average_weights = np.mean(weights, axis=-2).reshape(weights[:,:,-1:,:].shape)  #Find mean along the channel axis (second to last axis)\n  return(average_weights)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg_updated_config = vgg_updated.get_config()\nvgg_updated_layer_names = [vgg_updated_config['layers'][x]['name'] for x in range(len(vgg_updated_config['layers']))]\nfirst_conv_name = vgg_updated_layer_names[1]\nfirst_conv_name","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in vgg_model.layers:\n    if layer.name in vgg_updated_layer_names:\n     \n      if layer.get_weights() != []:  #All convolutional layers and layers with weights (no input layer or any pool layers)\n        target_layer = vgg_updated.get_layer(layer.name)\n    \n        if layer.name in first_conv_name:    #For the first convolutionl layer\n          weights = layer.get_weights()[0]\n          biases  = layer.get_weights()[1]\n          \n          weights_single_channel = avg_wts(weights)\n                                                    \n          target_layer.set_weights([weights_single_channel, biases])  #Now set weights for the first conv. layer\n          target_layer.trainable = False   #You can make this trainable if you want. \n    \n        else:\n          target_layer.set_weights(layer.get_weights())   #Set weights to all other layers. \n          target_layer.trainable = False  #You can make this trainable if you want. ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in vgg_model.layers:\n    if layer.name in vgg_updated_layer_names:\n     \n      if layer.get_weights() != []:  #All convolutional layers and layers with weights (no input layer or any pool layers)\n        target_layer = vgg_updated.get_layer(layer.name)\n    \n        if layer.name in first_conv_name:    #For the first convolutionl layer\n          weights = layer.get_weights()[0]\n          biases  = layer.get_weights()[1]\n    \n          weights_extra_channels = avg_and_copy_wts(weights,2)\n                                                  \n          target_layer.set_weights([weights_extra_channels, biases])  #Now set weights for the first conv. layer\n          target_layer.trainable = False   #You can make this trainable if you want. \n    \n        else:\n          target_layer.set_weights(layer.get_weights())   #Set weights to all other layers. \n          target_layer.trainable = False  #You can make this trainable if you want.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg_updated.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model_conv1_block1_wts_updated = vgg_model.layers[1].get_weights()[0]\nprint(new_model_conv1_block1_wts_updated[:,:,2,0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model_conv1_block1_wts_updated = vgg_updated.layers[1].get_weights()[0]\nprint(new_model_conv1_block1_wts_updated[:,:,0,0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(0.34+0.46+0.39) / 3","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.layers[0].layers","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_Neural_Net= ResNet50(input_shape=(600,400,2), weights=None, include_top=False)\nmodel=Sequential()\n\n\nfor layer in base_Neural_Net.layers:\n    layer.trainable = True\n\nmodel.add(tf.keras.layers.RandomFlip(\n    mode=\"horizontal\", seed=None\n))\n\nmodel.add(tf.keras.layers.RandomZoom(\n    height_factor=(-0.2, -0.1),\n    width_factor=None,\n    fill_mode=\"constant\",\n    interpolation=\"bilinear\",\n    seed=None,\n    fill_value=0.0\n))\n\n    \nmodel.add(base_Neural_Net)\nmodel.add(Flatten())\n\n\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(128))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\n\nmodel.add(Dense(4,activation='softmax'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_model_conv1_block1_wts_updated = model.layers[0].layers[1].get_weights()[0]\nprint(new_model_conv1_block1_wts_updated[:,:,1,0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=Sequential()\n\n\nmodel.add(vgg_updated)\nmodel.add(Flatten())\n\n\nmodel.add(Dense(2048))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\n\n\nmodel.add(Dense(4,activation='softmax'))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(learning_rate=0.0001), loss=lossOrdinal, metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 16\ntrain_img = trainLoaderCM(batch_size)\nval_img = valLoaderCM(batch_size)\n#test_img = testLoaderCM(batch_size)\n\n\ns = len(train1) // batch_size\nv = len(val)// batch_size\nbest_weights_file=\"weights.best.hdf5\"\ncheckpoint = ModelCheckpoint(best_weights_file, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n\ncallbacks = [checkpoint]\n\n\nmodel.fit(train_img,\n          steps_per_epoch=s,\n          epochs=75,\n          verbose=1,\n          validation_data=val_img,\n          validation_steps=v\n         # ,sample_weight = classWeight\n         )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"density.h5\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_batch = valLoaderCM(100)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testimg , labels =  test_batch.__next__()\nprint(\"Performance Report: TeknoFest Density:\")\ny_pred6=model.predict(testimg)\ny_pred6=[np.argmax(x) for x in y_pred6]\n#y_pred6 = y_pred6 > 0.5\ny_test6=[np.argmax(x) for x in labels]\n#y_test6 = labels\n#y_pred_prb6=model.predict_proba(x_test)\ntarget=[\"A\",\"B\",\"C\",\"D\"]\nfrom sklearn import metrics\nprint('Accuracy score is :', np.round(metrics.accuracy_score(y_test6, y_pred6),4))\nprint('Precision score is :', np.round(metrics.precision_score(y_test6, y_pred6, average='weighted'),4))\nprint('Recall score is :', np.round(metrics.recall_score(y_test6,y_pred6, average='weighted'),4))\nprint('F1 Score is :', np.round(metrics.f1_score(y_test6, y_pred6, average='weighted'),4))\n#print('ROC AUC Score is :', np.round(metrics.roc_auc_score(y_test6, y_pred6,multi_class='ovo', average='weighted'),4))\nprint('Cohen Kappa Score:', np.round(metrics.cohen_kappa_score(y_test6, y_pred6),4))\nprint('\\t\\tClassification Report:\\n', metrics.classification_report(y_test6, y_pred6,target_names=target))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confusion_matrix(y_test6,y_pred6)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train_bal)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}