{"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":"\n# Machine Learning and Data Science Imports\nimport tensorflow_probability as tfp\nimport tensorflow_datasets as tfds\nimport tensorflow_addons as tfa\nimport tensorflow_hub as hub\nfrom skimage import exposure\nimport pandas as pd;\nimport numpy as np\nimport scipy\n\n# Built In Imports\nfrom datetime import datetime\nfrom glob import glob\nimport warnings\nimport IPython\nimport urllib\nimport zipfile\nimport pickle\nimport shutil\n\n# Machine Learning and Data Science Imports\nimport tensorflow_probability as tfp\nimport tensorflow_datasets as tfds\nimport tensorflow_addons as tfa\nimport tensorflow_hub as hub\nfrom skimage import exposure\nimport pandas as pd;\nimport numpy as np\nimport scipy\n\n# Built In Imports\nfrom datetime import datetime\nfrom glob import glob\nimport warnings\nimport IPython\nimport urllib\nimport zipfile\nimport pickle\nimport shutil\nimport string\nimport math\nimport tqdm\nimport time\nimport os\nimport gc\nimport re\n\n# Visualization Imports\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.patches as patches\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport seaborn as sns\nfrom PIL import Image\nimport matplotlib\nimport plotly\nimport PIL\nimport cv2\n\n# PRESETS\nFIG_FONT = dict(family=\"Helvetica, Arial\", size=14, color=\"#7f7f7f\")\nLABEL_COLORS = [px.colors.label_rgb(px.colors.convert_to_RGB_255(x)) for x in sns.color_palette(\"Spectral\", 15)]\n\n\n\nprint(\"\\n... IMPORTS COMPLETE ...\\n\")","metadata":{"execution":{"iopub.status.busy":"2021-09-29T07:56:51.241226Z","iopub.execute_input":"2021-09-29T07:56:51.241589Z","iopub.status.idle":"2021-09-29T07:56:55.104892Z","shell.execute_reply.started":"2021-09-29T07:56:51.241506Z","shell.execute_reply":"2021-09-29T07:56:55.103493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut","metadata":{"execution":{"iopub.status.busy":"2021-09-29T07:56:56.20629Z","iopub.execute_input":"2021-09-29T07:56:56.206843Z","iopub.status.idle":"2021-09-29T07:56:56.255587Z","shell.execute_reply.started":"2021-09-29T07:56:56.206806Z","shell.execute_reply":"2021-09-29T07:56:56.254781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" import tensorflow as tf\n from tensorflow.keras.preprocessing.image import ImageDataGenerator\n tf.random.set_seed(42)\n train_datagen=ImageDataGenerator(rescale=1./255)\n test_datagen=ImageDataGenerator(rescale=1./255)","metadata":{"execution":{"iopub.status.busy":"2021-09-29T07:56:56.738925Z","iopub.execute_input":"2021-09-29T07:56:56.739638Z","iopub.status.idle":"2021-09-29T07:56:56.74484Z","shell.execute_reply.started":"2021-09-29T07:56:56.739603Z","shell.execute_reply":"2021-09-29T07:56:56.743866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir=\"../input/vinbigdata-chest-xray-abnormalities-detection/train\"\ntest_dir=\"../input/vinbigdata-chest-xray-abnormalities-detection/test\"","metadata":{"execution":{"iopub.status.busy":"2021-09-29T07:56:58.139459Z","iopub.execute_input":"2021-09-29T07:56:58.14Z","iopub.status.idle":"2021-09-29T07:56:58.143753Z","shell.execute_reply.started":"2021-09-29T07:56:58.139961Z","shell.execute_reply":"2021-09-29T07:56:58.142925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data=train_datagen.flow_from_directory(train_dir,batch_size=32,target_size=(224,224),class_mode=\"categorical\",seed=42)\ntest_data=test_datagen.flow_from_directory(test_dir,batch_size=32,target_size=(224,224),class_mode=\"categorical\",seed=42)\n","metadata":{"execution":{"iopub.status.busy":"2021-09-29T07:57:36.203896Z","iopub.execute_input":"2021-09-29T07:57:36.204162Z","iopub.status.idle":"2021-09-29T07:57:40.817603Z","shell.execute_reply.started":"2021-09-29T07:57:36.204137Z","shell.execute_reply":"2021-09-29T07:57:40.815896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline\n\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    \n    return data","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.image as mpimg\nimport random\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target_folder=\"../input/vinbigdata-chest-xray-abnormalities-detection/train\"\nrandom_image=random.sample(os.listdir(target_folder),1)\npath=target_folder+\"/\"+random_image[0]\nimg=read_xray(path)\nplt.figure(figsize = (12,12))\nplt.title(random_image[0])\nplt.imshow(img, 'gray')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_DIR=\"../input/vinbigdata-chest-xray-abnormalities-detection\"\nTRAIN_CSV = os.path.join(DATA_DIR, \"train.csv\")\nSS_CSV = os.path.join(DATA_DIR, \"sample_submission.csv\")\n\n# Create the relevant dataframe objects\ntrain_df = pd.read_csv(TRAIN_CSV)\nss_df = pd.read_csv(SS_CSV)\n\nprint(\"\\n\\nTRAIN DATAFRAME\\n\\n\")\ndisplay(train_df.head(3))\n\nprint(\"\\n\\nSAMPLE SUBMISSION DATAFRAME\\n\\n\")\ndisplay(ss_df.head(3))\n\nprint(train_df['class_name'].value_counts())\nprint(train_df['rad_id'].value_counts())\nprint(train_df.columns)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dicom_paths = [os.path.join(train_dir, f_name) for f_name in os.listdir(train_dir)]\ntest_dicom_paths = [os.path.join(test_dir, f_name) for f_name in os.listdir(test_dir)]\nprint(f\"\\n... The number of training files is {len(train_dicom_paths)} ...\")\nprint(f\"... The number of testing files is {len(test_dicom_paths)} ...\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.histogram(train_df.image_id.value_counts(), \n                   log_y=True, color_discrete_sequence=['indianred'], opacity=0.7,\n                   labels={\"value\":\"Number of Annotations Per Image\"},\n                   title=\"<b>DISTRIBUTION OF # OF ANNOTATIONS PER PATIENT   \" \\\n                         \"<i><sub>(Log Scale for Y-Axis)</sub></i></b>\",\n                   )\nfig.update_layout(showlegend=False,\n                  xaxis_title=\"<b>Number of Unique Images</b>\",\n                  yaxis_title=\"<b>Count of All Object Annotations</b>\",\n                  font=FIG_FONT,)\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.histogram(train_df.groupby('image_id')[\"class_name\"].unique().apply(lambda x: len(x)), \n             log_y=True, color_discrete_sequence=['skyblue'], opacity=0.7,\n             labels={\"value\":\"Number of Unique Abnormalities\"},\n             title=\"<b>DISTRIBUTION OF # OF ANNOTATIONS PER PATIENT   \" \\\n                   \"<i><sub>(Log Scale for Y-Axis)</sub></i></b>\",\n                   )\nfig.update_layout(showlegend=False,\n                  xaxis_title=\"<b>Number of Unique Abnormalities</b>\",\n                  yaxis_title=\"<b>Count of Unique Patients</b>\",\n                  font=FIG_FONT,)\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.bar(train_df.class_name.value_counts().sort_index(), \n             color=train_df.class_name.value_counts().sort_index().index, opacity=0.85,\n             color_discrete_sequence=LABEL_COLORS, log_y=True,\n             labels={\"y\":\"Annotations Per Class\", \"x\":\"\"},\n             title=\"<b>Annotations Per Class</b>\",)\nfig.update_layout(legend_title=None,\n                  font=FIG_FONT,\n                  xaxis_title=\"\",\n                  yaxis_title=\"<b>Annotations Per Class</b>\")\n\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.histogram(train_df, x=\"rad_id\", color=\"rad_id\",opacity=0.85,\n                   labels={\"rad_id\":\"Radiologist ID\"},\n                   title=\"<b>DISTRIBUTION OF # OF ANNOTATIONS PER RADIOLOGIST</b>\",\n                   ).update_xaxes(categoryorder=\"total descending\")\nfig.update_layout(legend_title=\"<b>RADIOLOGIST ID</b>\",\n                  xaxis_title=\"<b>Radiologist ID</b>\",\n                  yaxis_title=\"<b>Number of Annotations Made</b>\",\n                  font=FIG_FONT,)\nfig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone https://github.com/ultralytics/yolov5","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%cd yolov5/","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}