{"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)\nimport pydicom as dicom\nimport matplotlib.pylab as plt\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\ndirvarname = {}\nfilevarname = {}\ni = 0\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname,filename))\n        if i == 0:\n            dirvarname[i] = dirname\n            filevarname[i] = filename\n        else:\n           dirvarname[i] = dirname\n           filevarname[i] = filename\n        i = i+1\n        \n        \n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-01-18T17:44:59.861939Z","iopub.execute_input":"2023-01-18T17:44:59.862362Z","iopub.status.idle":"2023-01-18T17:45:41.384557Z","shell.execute_reply.started":"2023-01-18T17:44:59.862327Z","shell.execute_reply":"2023-01-18T17:45:41.383219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# VISUALLY INSPECTING SOME OF THE DICOM BREAST IMAGES\nds = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/10006/1459541791.dcm')\nplt.imshow(ds.pixel_array, cmap='gray')\nplt.show()\nplt.imshow(np.diff(ds.pixel_array,1), cmap='gray')\nplt.show()\nplt.imshow(np.diff(ds.pixel_array,0), cmap='gray')\nplt.show()\n\nds2 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/10706/937109986.dcm')\nplt.imshow(ds2.pixel_array, cmap='gray')\nplt.show()\nds3 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/10706/34700621.dcm')\nplt.imshow(ds3.pixel_array, cmap='gray')\nplt.show()\nds4 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/10706/1167990339.dcm')\nplt.imshow(ds4.pixel_array, cmap='gray')\nplt.show()\n\nds5 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/21867/1291014447.dcm')\nplt.imshow(ds5.pixel_array, cmap='gray')\nplt.show()\nds6 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/21867/831671840.dcm')\nplt.imshow(ds6.pixel_array, cmap='gray')\nplt.show()\nds7 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/21867/1481837831.dcm')\nplt.imshow(ds7.pixel_array, cmap='gray')\nplt.show()\nds8 = dicom.dcmread('/kaggle/input/rsna-breast-cancer-detection/train_images/21867/851000290.dcm')\nplt.imshow(ds8.pixel_array, cmap='gray')\nplt.show()\nprint(filename)\nprint(dirname)","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:45:41.387317Z","iopub.execute_input":"2023-01-18T17:45:41.387814Z","iopub.status.idle":"2023-01-18T17:46:09.210524Z","shell.execute_reply.started":"2023-01-18T17:45:41.387763Z","shell.execute_reply":"2023-01-18T17:46:09.209366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# SETTING UP THE LIBRARIES FOR THE DEEP LEARNIGN CNN\nimport numpy as np\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras import Sequential\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import * \nfrom tensorflow.keras.preprocessing import image\nimport pandas as pd\nimport scipy as scp\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPool2D\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Dense\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:46:09.211691Z","iopub.execute_input":"2023-01-18T17:46:09.212007Z","iopub.status.idle":"2023-01-18T17:46:15.831442Z","shell.execute_reply.started":"2023-01-18T17:46:09.211978Z","shell.execute_reply":"2023-01-18T17:46:15.830076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# exploring the train.csv and test.csv datasets \ntrain_path= \"/kaggel/input/rsna-breast-cancer-detection/train_images\"\ntest_path=\"/kaggel/input/rsna-breast-cancer-detection/test_images\"\n\n\ntrain_info = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/train.csv', delimiter=',')\ntest_info = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/test.csv', delimiter=',')\nprint(train_info)\nprint(train_info[\"patient_id\"])\nprint(train_info[\"image_id\"])\nprint(train_info[\"cancer\"])\nprint(str(dirvarname[0]))\nprint(str(train_info[\"patient_id\"][0]))","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:46:15.833267Z","iopub.execute_input":"2023-01-18T17:46:15.834014Z","iopub.status.idle":"2023-01-18T17:46:15.9792Z","shell.execute_reply.started":"2023-01-18T17:46:15.833972Z","shell.execute_reply":"2023-01-18T17:46:15.978223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"raw","source":"# find the correnpoding patient_id code path and image_id to match the \n# cancer label for in the train.csv\n\nloc_pat_id = {}\nfor i in range(0,len(train_info[\"patient_id\"])):\n    for k in range(0,len(dirvarname)):\n        fond_indx = dirvarname[k].find(str(train_info[\"patient_id\"][i]))\n        if fond_indx != -1:\n            loc_pat_id[i] = k\n            \nloc_img_id = {}\nfor u in range(0,len(train_info[\"image_id\"])):\n    for p in range(0,len(filevarname)):\n        fond_indx = filevarname[p].find(str(train_info[\"image_id\"][u]))\n        if fond_indx != -1:\n            loc_img_id[u] = p\n              ","metadata":{"execution":{"iopub.status.busy":"2023-01-07T17:11:50.642055Z","iopub.execute_input":"2023-01-07T17:11:50.642513Z"}}},{"cell_type":"code","source":"# find the correnpoding patient_id code path and image_id to match the \n# cancer label for in the train.csv\n\nloc_pat_id = {}\nfor i in range(0,100):# len(train_info[\"patient_id\"])\n    for k in range(0,len(dirvarname)):\n        fond_indx = dirvarname[k].find(str(train_info[\"patient_id\"][i]))\n        if fond_indx != -1:\n            loc_pat_id[i] = k\n            \nloc_img_id = {}\nfor u in range(0, 100):# len(train_info[\"image_id\"])\n    for p in range(0,len(filevarname)):\n        fond_indx = filevarname[p].find(str(train_info[\"image_id\"][u]))\n        if fond_indx != -1:\n            loc_img_id[u] = p\n              \n","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:46:15.981615Z","iopub.execute_input":"2023-01-18T17:46:15.982518Z","iopub.status.idle":"2023-01-18T17:47:36.784171Z","shell.execute_reply.started":"2023-01-18T17:46:15.982433Z","shell.execute_reply":"2023-01-18T17:47:36.782832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(filevarname[loc_img_id[1]])\nprint(dirvarname[loc_pat_id[1]])","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:47:36.786229Z","iopub.execute_input":"2023-01-18T17:47:36.786774Z","iopub.status.idle":"2023-01-18T17:47:36.793104Z","shell.execute_reply.started":"2023-01-18T17:47:36.786724Z","shell.execute_reply":"2023-01-18T17:47:36.79202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nfrom skimage.transform import resize\nfrom PIL import Image\n#import pylibjpeg\nX_train = []\nX_test = []\ny_train = []\n# setting up train image and labels for training Deep network\ny = train_info[\"cancer\"]\nprint(len(y))\nnon_can_indx={}\ncan_indx = {}\nindx = {}\na = 0\nb = 0\ny\nfor l in range(3,len(y)):\n    if y[l] == 0:\n        non_can_indx[a] = l   #non_can_indx.append(l)\n        a = a + 1\n    elif y[l] == 1:\n        can_indx[b] = l   #can_indx.append(l)\n        b = b + 1\nprint(non_can_indx[1])\nprint(can_indx[1])\n\nfor u in range(0, len(non_can_indx)):\n    indx[u] = non_can_indx[u]\n    y_train.append(0)\nfor t in range(0,len(can_indx)):\n    indx[t+len(non_can_indx)+1]=can_indx[t]\n    y_train.append(1)\nindx = [non_can_indx[0],non_can_indx[1], non_can_indx[2], non_can_indx[3], non_can_indx[4], non_can_indx[6], non_can_indx[7], can_indx[0], can_indx[1], can_indx[2], can_indx[3], can_indx[4], can_indx[6],can_indx[7]]\nprint(len(indx))\nprint(len(non_can_indx))\n\n#y_train = [np.zeros(len(non_can_indx)), np.ones(len(can_indx))]\n#indx_test = [non_can_indx[6],can_indx[5]]\nfor i in range(0,len(indx)):\n    # resample image so that all images have the same dimensions\n    print(os.path.join(dirvarname[indx[i]],filevarname[indx[i]]))\n    img = dicom.dcmread(os.path.join(dirvarname[indx[i]],filevarname[indx[i]]))\n    img.PhotometricInterpretation = 'YBR_FULL'\n    X_train.append(resize(img.pixel_array, (256, 256)))\ny_train = [0 ,0 ,0, 0, 0, 0,0, 1,1,1,1,1,1,1]\n#for j in range(0,len(indx_test)):\n#    print(os.path.join(dirvarname[indx_test[j]],filevarname[indx_test[j]]))\n#    img_test = dicom.dcmread(os.path.join(dirvarname[indx_test[j]],filevarname[indx_test[j]]))\n#    X_test.append(resize(img_test.pixel_array, (256, 256)))\n    \n\n#y_test = [0, 1]","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:47:36.794891Z","iopub.execute_input":"2023-01-18T17:47:36.795409Z","iopub.status.idle":"2023-01-18T17:48:18.369949Z","shell.execute_reply.started":"2023-01-18T17:47:36.795363Z","shell.execute_reply":"2023-01-18T17:48:18.368601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = image.ImageDataGenerator(\n    rotation_range=15,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\nval_datagen= image.ImageDataGenerator(    rotation_range=15,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    width_shift_range=0.1,\n    height_shift_range=0.1)\n\ndatagen = ImageDataGenerator(\n            rescale=1./ 255,\n               rotation_range=260,\n               featurewise_std_normalization=True,\n                horizontal_flip=True,vertical_flip=True\n    \n                )","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:18.371681Z","iopub.execute_input":"2023-01-18T17:48:18.372089Z","iopub.status.idle":"2023-01-18T17:48:18.382576Z","shell.execute_reply.started":"2023-01-18T17:48:18.372047Z","shell.execute_reply":"2023-01-18T17:48:18.381622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path= \"/kaggle/input/rsna-breast-cancer-detection/train_images\"\ntest_path=\"/kaggle/input/rsna-breast-cancer-detection/test_images\"","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:18.384086Z","iopub.execute_input":"2023-01-18T17:48:18.384557Z","iopub.status.idle":"2023-01-18T17:48:18.397303Z","shell.execute_reply.started":"2023-01-18T17:48:18.384514Z","shell.execute_reply":"2023-01-18T17:48:18.395633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data=datagen.flow_from_directory(train_path, target_size=(256, 256), color_mode='grayscale', classes=None, class_mode='categorical', batch_size=32, interpolation='nearest')\ntest_data=datagen.flow_from_directory(test_path, target_size=(256, 256), color_mode='grayscale', classes=None, class_mode='categorical', batch_size=32, interpolation='nearest')","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:18.398689Z","iopub.execute_input":"2023-01-18T17:48:18.399053Z","iopub.status.idle":"2023-01-18T17:48:27.835517Z","shell.execute_reply.started":"2023-01-18T17:48:18.399022Z","shell.execute_reply":"2023-01-18T17:48:27.834567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    train_path,\n    target_size = (256,256, 1),\n    batch_size = 4,\n    class_mode = 'binary')\nvalidation_generator = val_datagen.flow_from_directory(\n    test_path,\n    target_size = (256,256, 1),\n    batch_size = 4,\n    shuffle=True,\n    class_mode = 'binary')","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:27.836985Z","iopub.execute_input":"2023-01-18T17:48:27.837637Z","iopub.status.idle":"2023-01-18T17:48:30.375965Z","shell.execute_reply.started":"2023-01-18T17:48:27.837601Z","shell.execute_reply":"2023-01-18T17:48:30.374565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=(256,256,3)))\nmodel.add(Conv2D(32,kernel_size=(3,3),activation='sigmoid'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(64,kernel_size=(3,3),activation='relu'))\nmodel.add(Conv2D(64,kernel_size=(3,3),activation='sigmoid'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(128,kernel_size=(3,3),activation='relu'))\nmodel.add(Conv2D(128,kernel_size=(3,3),activation='sigmoid'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(GaussianNoise(0.25))\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(64,activation='relu'))# before it was relu \nmodel.add(GaussianNoise(0.25))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:30.377816Z","iopub.execute_input":"2023-01-18T17:48:30.378318Z","iopub.status.idle":"2023-01-18T17:48:30.587949Z","shell.execute_reply.started":"2023-01-18T17:48:30.378268Z","shell.execute_reply":"2023-01-18T17:48:30.586839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy','AUC','Precision','Recall'])","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:30.589345Z","iopub.execute_input":"2023-01-18T17:48:30.58971Z","iopub.status.idle":"2023-01-18T17:48:30.607104Z","shell.execute_reply.started":"2023-01-18T17:48:30.589677Z","shell.execute_reply":"2023-01-18T17:48:30.605747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom sklearn.model_selection import train_test_split\nfrom skimage.color import gray2rgb\n#es=EarlyStopping(patience=3,monitor='val_loss')\n#filepath='best_model.h5'\n#checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')\n#history = model.fit(\n#    train_generator,\n#    epochs=10,\n#    validation_data=validation_generator,\n#    steps_per_epoch= 50,\n#    callbacks=checkpoint\n #   )\nX_train_d, X_test_d, y_train_d, y_test_d = train_test_split(X_train, y_train, test_size = 0.3, random_state = 82, shuffle=True)\nprint(len(X_train_d))\nprint(len(y_train_d))\nprint(len(X_test_d))\nprint(len(y_test_d))\n# Convert the lists to arrays\nX_train_d2 = np.asarray(X_train_d)\nX_test_d2 = np.asarray(X_test_d)\ny_train_d2 = np.asarray(y_train_d)\ny_test_d2 = np.asarray(y_test_d)\n\n# Reshape the images to 3 channels\nX_train_d3= gray2rgb(X_train_d2)\nX_test_d3 = gray2rgb(X_test_d2)\nhistory = model.fit(X_train_d3,y_train_d2,batch_size=2, epochs=4,verbose=1,validation_data=(X_test_d3, y_test_d2))#,validation_data=(X_test,y_test)","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:30.612027Z","iopub.execute_input":"2023-01-18T17:48:30.612422Z","iopub.status.idle":"2023-01-18T17:48:40.141121Z","shell.execute_reply.started":"2023-01-18T17:48:30.612389Z","shell.execute_reply":"2023-01-18T17:48:40.139771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"p = 0\nk = 0\nimage_id = {}\ny_predict = {}\nfor dirname, _, filenames in os.walk(test_path):\n    for filename in filenames:\n        print(os.path.join(dirname,filename))\n        test_img = os.path.join(dirname,filename)\n        image_id[p]=filename\n        p=p+1\n        img = dicom.dcmread(test_img)\n        imag = gray2rgb(np.asarray(resize(img.pixel_array, (256, 256))))\n        imag = imag.reshape(1, 256, 256, 3)\n#imaga = np.expand_dims(imag,axis=0) \n        print(np.shape(imag))\n        ypred = model.predict(imag)\n        print(ypred)\n        a=ypred[0]\n        if a<0.5:\n              op=\"Healthy\"\n              y_predict[k]=0\n        else:\n              op=\"Cancer\"\n              y_predict[k]=1\n        plt.imshow(img.pixel_array)\n        \n        print(\"THE UPLOADED IMAGE IS SUSPECTED AS: \"+str(op)) \n        k = k+1","metadata":{"execution":{"iopub.status.busy":"2023-01-18T17:48:40.142842Z","iopub.execute_input":"2023-01-18T17:48:40.143667Z","iopub.status.idle":"2023-01-18T17:48:48.945467Z","shell.execute_reply.started":"2023-01-18T17:48:40.14362Z","shell.execute_reply":"2023-01-18T17:48:48.944547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/sample_submission.csv\")\ntest_info[\"patient_id\"]\nimage_id\nsample = {}\n#laterality_pst={}\n#for j in range(0,len(image_id)):\n   # indx_img_id = test_info[\"image_id\"].find(image_id[j])\n   # laterality_pst[j] = test_info[\"laterality\"][indx_img_id]\ny_predict\nsample[\"patient_id\"]= test_info[\"patient_id\"]\nsample[\"image_id\"]= image_id\nsample[\"Cancer\"]=y_predict\nsample_2 = pd.DataFrame(sample)\nsample_2.to_csv(\"submission.csv\", index=False)\nsample_2","metadata":{"execution":{"iopub.status.busy":"2023-01-18T18:22:44.987424Z","iopub.execute_input":"2023-01-18T18:22:44.987922Z","iopub.status.idle":"2023-01-18T18:22:45.019811Z","shell.execute_reply.started":"2023-01-18T18:22:44.987882Z","shell.execute_reply":"2023-01-18T18:22:45.018641Z"},"trusted":true},"execution_count":null,"outputs":[]}]}