{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10338,"databundleVersionId":862042,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\n# import os\n# for 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":{"iopub.status.busy":"2025-06-24T12:35:02.346614Z","iopub.execute_input":"2025-06-24T12:35:02.346884Z","iopub.status.idle":"2025-06-24T12:35:02.351747Z","shell.execute_reply.started":"2025-06-24T12:35:02.346865Z","shell.execute_reply":"2025-06-24T12:35:02.350697Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We will be using Pandas, fastai to do a very basic  (far from what's asked in challenge) image classifier to predict pneumonia.\nWe will use `fastai.medical.imaging` to parse `DiCom` images.\n\nlet's parse and loade the data.","metadata":{}},{"cell_type":"code","source":"from fastai.vision.all import *\nfrom fastai.medical.imaging import *\n\nprint(\"fastai is ready!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T12:35:02.353913Z","iopub.execute_input":"2025-06-24T12:35:02.354477Z","iopub.status.idle":"2025-06-24T12:35:06.139465Z","shell.execute_reply.started":"2025-06-24T12:35:02.354448Z","shell.execute_reply":"2025-06-24T12:35:06.138514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def parse_data(df):\n    extract_box = lambda row: [row['y'], row['x'], row['height'], row['width']]\n\n    parsed = {}\n\n    for _, row in df.iterrows():\n        pid = row['patientId']\n        if pid not in parsed:\n            parsed[pid] = {\n                'dicom':  f'/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_images/{pid}.dcm',\n                'label': row['Target'],\n                'boxes': [],\n                \"class_info\": row['class']\n            }\n\n        if parsed[pid]['label'] == 1:\n            parsed[pid]['boxes'].append(extract_box(row))\n\n    return parsed\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:15:01.674414Z","iopub.execute_input":"2025-06-24T16:15:01.674729Z","iopub.status.idle":"2025-06-24T16:15:01.681044Z","shell.execute_reply.started":"2025-06-24T16:15:01.674709Z","shell.execute_reply":"2025-06-24T16:15:01.680001Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"The `parsed_data` method loads the CSV file and spits an array of dict in the format printed below","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_train_labels.csv')\ndf_info = pd.read_csv('/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv')\ndf_merged = df_info.merge(df, on='patientId')\n\nparsed = parse_data( df_merged.groupby('class', group_keys=False)\n    .apply(lambda x: x.sample(n=min(500, len(x)), random_state=42)))\n\nprint(f\"Parsed {len(parsed)} patients\")\n\nlist(parsed.items())[:2]  # Show first 2 entries","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:15:13.431040Z","iopub.execute_input":"2025-06-24T16:15:13.431361Z","iopub.status.idle":"2025-06-24T16:15:13.643750Z","shell.execute_reply.started":"2025-06-24T16:15:13.431337Z","shell.execute_reply":"2025-06-24T16:15:13.642744Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Now that we've loaded + parsed data. Let's build  DataBlock + DataLoaders and visualize them in batches.\n\nNote: We cannot using the ImageDataLoaders here since the images are not categorized in folders but rather feeded to us in dictionary. plus, DataBlock is a lower leve and offers more flexibility.","metadata":{}},{"cell_type":"code","source":"def get_x(o):\n    return o['dicom']\n\ndef get_y(o):\n    return str(o['label'])\n\nitems = list(parsed.values())\n\ndblock = DataBlock(\n    blocks=(ImageBlock(cls=PILDicom), CategoryBlock),\n    get_x=get_x,\n    get_y=get_y,\n    splitter=RandomSplitter(seed=42),\n    item_tfms=Resize(224),\n    batch_tfms=aug_transforms()\n)\n\ndls = dblock.dataloaders(items, bs=32)\n\ndls.show_batch(max_n=9, figsize=(8,8))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:15:24.544350Z","iopub.execute_input":"2025-06-24T16:15:24.544647Z","iopub.status.idle":"2025-06-24T16:15:26.577805Z","shell.execute_reply.started":"2025-06-24T16:15:24.544628Z","shell.execute_reply":"2025-06-24T16:15:26.576880Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Next Step: Create our learner\n\nlet's\n- Build a model (ResNet)\n- Attach it to our dls\n- setup a metric (eg: accuracy)","metadata":{}},{"cell_type":"code","source":"learn = vision_learner(dls, resnet34, metrics=accuracy)\n\n# learn.lr_find()\n\nlearn.fine_tune(2, base_lr=1e-3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:28:48.440492Z","iopub.execute_input":"2025-06-24T16:28:48.440860Z","iopub.status.idle":"2025-06-24T16:41:49.429433Z","shell.execute_reply.started":"2025-06-24T16:28:48.440825Z","shell.execute_reply":"2025-06-24T16:41:49.428417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"learn.export()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:41:59.458594Z","iopub.execute_input":"2025-06-24T16:41:59.458901Z","iopub.status.idle":"2025-06-24T16:41:59.732372Z","shell.execute_reply.started":"2025-06-24T16:41:59.458881Z","shell.execute_reply":"2025-06-24T16:41:59.731571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from fastai.vision.all import ClassificationInterpretation\n\ninterp = ClassificationInterpretation.from_learner(learn)\n\ninterp.plot_confusion_matrix()\ninterp.plot_top_losses(9, figsize=(8,8))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T16:42:28.613877Z","iopub.execute_input":"2025-06-24T16:42:28.614827Z","iopub.status.idle":"2025-06-24T16:43:17.216420Z","shell.execute_reply.started":"2025-06-24T16:42:28.614797Z","shell.execute_reply":"2025-06-24T16:43:17.215466Z"}},"outputs":[],"execution_count":null}]}