{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"}],"dockerImageVersionId":30732,"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\nimport os\n\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":"2024-06-28T17:29:36.790235Z","iopub.execute_input":"2024-06-28T17:29:36.790626Z","iopub.status.idle":"2024-06-28T17:29:37.169261Z","shell.execute_reply.started":"2024-06-28T17:29:36.790598Z","shell.execute_reply":"2024-06-28T17:29:37.168426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\n\nimport matplotlib.pyplot as plt\nimport os\nimport time\nimport numpy as np\nimport glob\nimport json\nimport collections\nimport torch\nimport torch.nn as nn\n\nimport pydicom as dicom\nimport matplotlib.patches as patches\n\nfrom matplotlib import animation, rc\nimport pandas as pd\n\nimport pydicom as dicom # dicom\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut","metadata":{"execution":{"iopub.status.busy":"2024-06-28T17:29:41.842101Z","iopub.execute_input":"2024-06-28T17:29:41.842622Z","iopub.status.idle":"2024-06-28T17:29:45.291131Z","shell.execute_reply.started":"2024-06-28T17:29:41.842588Z","shell.execute_reply":"2024-06-28T17:29:45.290099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# read data\ntrain_path = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/'\n\ntrain  = pd.read_csv(train_path + 'train.csv')\nlabel = pd.read_csv(train_path + 'train_label_coordinates.csv')\ntrain_desc  = pd.read_csv(train_path + 'train_series_descriptions.csv')\ntest_desc   = pd.read_csv(train_path + 'test_series_descriptions.csv')\nsub         = pd.read_csv(train_path + 'sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-06-28T17:29:48.537476Z","iopub.execute_input":"2024-06-28T17:29:48.538335Z","iopub.status.idle":"2024-06-28T17:29:48.692601Z","shell.execute_reply.started":"2024-06-28T17:29:48.538299Z","shell.execute_reply":"2024-06-28T17:29:48.691560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"subtest = sub","metadata":{"execution":{"iopub.status.busy":"2024-06-26T14:38:38.731730Z","iopub.execute_input":"2024-06-26T14:38:38.732214Z","iopub.status.idle":"2024-06-26T14:38:38.737923Z","shell.execute_reply.started":"2024-06-26T14:38:38.732179Z","shell.execute_reply":"2024-06-26T14:38:38.736502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dff = pd.DataFrame(np.random.randint(1000,9000,size=(100, 1)), columns=[\"row_id\"])","metadata":{"execution":{"iopub.status.busy":"2024-06-28T17:29:50.490584Z","iopub.execute_input":"2024-06-28T17:29:50.491285Z","iopub.status.idle":"2024-06-28T17:29:50.510419Z","shell.execute_reply.started":"2024-06-28T17:29:50.491250Z","shell.execute_reply":"2024-06-28T17:29:50.509320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dff","metadata":{"execution":{"iopub.status.busy":"2024-06-28T17:29:58.729152Z","iopub.execute_input":"2024-06-28T17:29:58.729556Z","iopub.status.idle":"2024-06-28T17:29:58.749179Z","shell.execute_reply.started":"2024-06-28T17:29:58.729526Z","shell.execute_reply":"2024-06-28T17:29:58.747929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncsv_file_path = sub\ndf = sub\n \n# Step 2: Define the values for the new \"City\" column\nnew_city_values = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']\n \n# Step 3: Add the new \"City\" column to the DataFrame\ndf['City'] \n \n# Step 4: Write the DataFrame back to the CSV file\ndf.to_csv(csv_file_path, index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-26T15:13:09.075917Z","iopub.execute_input":"2024-06-26T15:13:09.076910Z","iopub.status.idle":"2024-06-26T15:13:09.266737Z","shell.execute_reply.started":"2024-06-26T15:13:09.076854Z","shell.execute_reply":"2024-06-26T15:13:09.265078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:27:59.310722Z","iopub.execute_input":"2024-06-25T14:27:59.311142Z","iopub.status.idle":"2024-06-25T14:27:59.344855Z","shell.execute_reply.started":"2024-06-25T14:27:59.311094Z","shell.execute_reply":"2024-06-25T14:27:59.343212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to generate image paths based on directory structure\ndef generate_image_paths(df, data_dir):\n    image_paths = []\n    for study_id, series_id in zip(df['study_id'], df['series_id']):\n        study_dir = os.path.join(data_dir, str(study_id))\n        series_dir = os.path.join(study_dir, str(series_id))\n        images = os.listdir(series_dir)\n        image_paths.extend([os.path.join(series_dir, img) for img in images])\n    return image_paths\n\n# Generate image paths for train and test data\ntrain_image_paths = generate_image_paths(train_desc, f'{train_path}/train_images')\ntest_image_paths = generate_image_paths(test_desc, f'{train_path}/test_images')","metadata":{"execution":{"iopub.status.busy":"2024-06-26T14:10:05.015050Z","iopub.execute_input":"2024-06-26T14:10:05.015451Z","iopub.status.idle":"2024-06-26T14:11:06.572251Z","shell.execute_reply.started":"2024-06-26T14:10:05.015420Z","shell.execute_reply":"2024-06-26T14:11:06.571062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train_desc)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:29:38.746719Z","iopub.execute_input":"2024-06-25T14:29:38.747296Z","iopub.status.idle":"2024-06-25T14:29:38.756652Z","shell.execute_reply.started":"2024-06-25T14:29:38.747256Z","shell.execute_reply":"2024-06-25T14:29:38.755227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pydicom\nimport matplotlib.pyplot as plt\n\n# Function to open and display DICOM images\ndef display_dicom_images(image_paths):\n    plt.figure(figsize=(15, 5))  # Adjust figure size if needed\n    for i, path in enumerate(image_paths[:3]):\n        ds = pydicom.dcmread(path)\n        plt.subplot(1, 3, i+1)\n        plt.imshow(ds.pixel_array, cmap=plt.cm.bone)\n        plt.title(f\"Image {i+1}\")\n        plt.axis('off')\n    plt.show()\n\n# Display the first three DICOM images\ndisplay_dicom_images(train_image_paths)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T14:12:32.479831Z","iopub.execute_input":"2024-06-26T14:12:32.480240Z","iopub.status.idle":"2024-06-26T14:12:33.183785Z","shell.execute_reply.started":"2024-06-26T14:12:32.480207Z","shell.execute_reply":"2024-06-26T14:12:33.182587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pydicom\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Function to open and display DICOM images along with coordinates\ndef display_dicom_with_coordinates(image_paths, label_df):\n    fig, axs = plt.subplots(1, len(image_paths), figsize=(18, 6))\n    \n    for idx, path in enumerate(image_paths):  # Display images\n        study_id = int(path.split('/')[-3])\n        series_id = int(path.split('/')[-2])\n        \n        # Filter label coordinates for the current study and series\n        filtered_labels = label_df[(label_df['study_id'] == study_id) & (label_df['series_id'] == series_id)]\n        \n        # Read DICOM image\n        ds = pydicom.dcmread(path)\n        \n        # Plot DICOM image\n        axs[idx].imshow(ds.pixel_array, cmap='gray')\n        axs[idx].set_title(f\"Study ID: {study_id}, Series ID: {series_id}\")\n        axs[idx].axis('off')\n        \n        # Plot coordinates\n        for _, row in filtered_labels.iterrows():\n            axs[idx].plot(row['x'], row['y'], 'ro', markersize=5)\n        \n    plt.tight_layout()\n    plt.show()\n\n# Load DICOM files from a folder\ndef load_dicom_files(path_to_folder):\n    files = [os.path.join(path_to_folder, f) for f in os.listdir(path_to_folder) if f.endswith('.dcm')]\n    files.sort(key=lambda x: int(os.path.splitext(os.path.basename(x))[0].split('-')[-1]))\n    return files\n\n# Display DICOM images with coordinates\nstudy_id = \"100206310\"\nstudy_folder = f'{train_path}/train_images/{study_id}'\n\nimage_paths = []\nfor series_folder in os.listdir(study_folder):\n    series_folder_path = os.path.join(study_folder, series_folder)\n    dicom_files = load_dicom_files(series_folder_path)\n    if dicom_files:\n        image_paths.append(dicom_files[0])  # Add the first image from each series\n\n\ndisplay_dicom_with_coordinates(image_paths, label)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T14:12:36.903732Z","iopub.execute_input":"2024-06-26T14:12:36.904177Z","iopub.status.idle":"2024-06-26T14:12:37.940971Z","shell.execute_reply.started":"2024-06-26T14:12:36.904143Z","shell.execute_reply":"2024-06-26T14:12:37.939838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define function to reshape a single row of the DataFrame\ndef reshape_row(row):\n    data = {'row_id': [], 'condition': [], 'level': [], 'severity': []}\n    \n    for column, value in row.items():\n        if column not in ['row_id', 'series_id', 'instance_number', 'x', 'y', 'series_description']:\n            parts = column.split('_')\n            condition = ' '.join([word.capitalize() for word in parts[:-1]])\n            level = parts[-1].capitalize() + '/' + parts[-1].capitalize()\n            data['row_id'].append(row['row_id'])\n            data['condition'].append(condition)\n            data['level'].append(level)\n            data['severity'].append(value)\n    \n    return pd.DataFrame(data)\n\n# Reshape the DataFrame for all rows\nnew_sub_df = pd.concat([reshape_row(row) for _, row in sub.iterrows()], ignore_index=True)\n\n# Display the first few rows of the reshaped dataframe\nnew_sub_df.head(15)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T14:22:40.461366Z","iopub.execute_input":"2024-06-26T14:22:40.461791Z","iopub.status.idle":"2024-06-26T14:22:40.491750Z","shell.execute_reply.started":"2024-06-26T14:22:40.461760Z","shell.execute_reply":"2024-06-26T14:22:40.490665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print columns in a neat way\nprint(\"\\nColumns in new_train_df:\")\nprint(\",\".join(new_train_df.columns))\n\nprint(\"\\nColumns in label:\")\nprint(\",\".join(label.columns))\n\nprint(\"\\nColumns in test_desc:\")\nprint(\",\".join(test_desc.columns))\n\nprint(\"\\nColumns in sub:\")\nprint(\",\".join(sub.columns))","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:46:49.735320Z","iopub.execute_input":"2024-06-25T14:46:49.735802Z","iopub.status.idle":"2024-06-25T14:46:49.744987Z","shell.execute_reply.started":"2024-06-25T14:46:49.735765Z","shell.execute_reply":"2024-06-25T14:46:49.743267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Merge the dataframes on the common columns\nmerged_df = pd.merge(new_train_df, label, on=['study_id', 'condition', 'level'], how='inner')\n# Merge the dataframes on the common column 'series_id'\nfinal_merged_df = pd.merge(merged_df, train_desc, on='series_id', how='inner')","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:47:40.983142Z","iopub.execute_input":"2024-06-25T14:47:40.983722Z","iopub.status.idle":"2024-06-25T14:47:41.083798Z","shell.execute_reply.started":"2024-06-25T14:47:40.983678Z","shell.execute_reply":"2024-06-25T14:47:41.082553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Merge the dataframes on the common column 'series_id'\nfinal_merged_df = pd.merge(merged_df, train_desc, on=['series_id','study_id'], how='inner')\n# Display the first few rows of the final merged dataframe\nfinal_merged_df.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:48:08.846087Z","iopub.execute_input":"2024-06-25T14:48:08.847122Z","iopub.status.idle":"2024-06-25T14:48:08.881228Z","shell.execute_reply.started":"2024-06-25T14:48:08.847063Z","shell.execute_reply":"2024-06-25T14:48:08.879954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_merged_df[final_merged_df['study_id'] == 100206310].sort_values(['x','y'],ascending = True)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:48:27.781685Z","iopub.execute_input":"2024-06-25T14:48:27.782185Z","iopub.status.idle":"2024-06-25T14:48:27.812722Z","shell.execute_reply.started":"2024-06-25T14:48:27.782147Z","shell.execute_reply":"2024-06-25T14:48:27.811226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_merged_df[final_merged_df['series_id'] == 1012284084].sort_values(\"instance_number\")","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:48:40.247256Z","iopub.execute_input":"2024-06-25T14:48:40.247818Z","iopub.status.idle":"2024-06-25T14:48:40.272727Z","shell.execute_reply.started":"2024-06-25T14:48:40.247780Z","shell.execute_reply":"2024-06-25T14:48:40.271224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Filter the dataframe for the given study_id and sort by instance_number\nfiltered_df = final_merged_df[final_merged_df['study_id'] == 1013589491].sort_values(\"instance_number\")\n\n# Display the resulting dataframe\nfiltered_df","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:49:55.646653Z","iopub.execute_input":"2024-06-25T14:49:55.647173Z","iopub.status.idle":"2024-06-25T14:49:55.674333Z","shell.execute_reply.started":"2024-06-25T14:49:55.647136Z","shell.execute_reply":"2024-06-25T14:49:55.673182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sort final_merged_df by study_id, series_id, and series_description\nsorted_final_merged_df = final_merged_df[final_merged_df['study_id'] == 1013589491].sort_values(by=['series_id', 'series_description', 'instance_number'])\nsorted_final_merged_df","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:50:18.757147Z","iopub.execute_input":"2024-06-25T14:50:18.757614Z","iopub.status.idle":"2024-06-25T14:50:18.788303Z","shell.execute_reply.started":"2024-06-25T14:50:18.757580Z","shell.execute_reply":"2024-06-25T14:50:18.786846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n# Create the row_id column\nfinal_merged_df['row_id'] = (\n    final_merged_df['study_id'].astype(str) + '_' +\n    final_merged_df['condition'].str.lower().str.replace(' ', '_') + '_' +\n    final_merged_df['level'].str.lower().str.replace('/', '_')\n)\n\n# Create the image_path column\nfinal_merged_df['image_path'] = (\n    f'{train_path}/train_images/' + \n    final_merged_df['study_id'].astype(str) + '/' +\n    final_merged_df['series_id'].astype(str) + '/' +\n    final_merged_df['instance_number'].astype(str) + '.dcm'\n)\n\n# Note: Check image path, since there's 1 instance id, for 1 image, but there's many more images other than the ones labelled in the instance ID. \n\n# Display the updated dataframe\nfinal_merged_df.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:51:10.853338Z","iopub.execute_input":"2024-06-25T14:51:10.853772Z","iopub.status.idle":"2024-06-25T14:51:11.174174Z","shell.execute_reply.started":"2024-06-25T14:51:10.853741Z","shell.execute_reply":"2024-06-25T14:51:11.172565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Normal/Mild\"].value_counts().sum()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:53:41.038152Z","iopub.execute_input":"2024-06-25T14:53:41.039127Z","iopub.status.idle":"2024-06-25T14:53:41.272757Z","shell.execute_reply.started":"2024-06-25T14:53:41.039063Z","shell.execute_reply":"2024-06-25T14:53:41.271210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Moderate\"].value_counts().sum()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:54:06.092755Z","iopub.execute_input":"2024-06-25T14:54:06.093254Z","iopub.status.idle":"2024-06-25T14:54:06.167684Z","shell.execute_reply.started":"2024-06-25T14:54:06.093217Z","shell.execute_reply":"2024-06-25T14:54:06.166211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the base path for test images\nbase_path = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/test_images/'\n\n# Function to get image paths for a series\ndef get_image_paths(row):\n    series_path = os.path.join(base_path, str(row['study_id']), str(row['series_id']))\n    if os.path.exists(series_path):\n        return [os.path.join(series_path, f) for f in os.listdir(series_path) if os.path.isfile(os.path.join(series_path, f))]\n    return []\n\n# Mapping of series_description to conditions\ncondition_mapping = {\n    'Sagittal T1': {'left': 'left_neural_foraminal_narrowing', 'right': 'right_neural_foraminal_narrowing'},\n    'Axial T2': {'left': 'left_subarticular_stenosis', 'right': 'right_subarticular_stenosis'},\n    'Sagittal T2/STIR': 'spinal_canal_stenosis'\n}\n\n# Create a list to store the expanded rows\nexpanded_rows = []\n\n# Expand the dataframe by adding new rows for each file path\nfor index, row in test_desc.iterrows():\n    image_paths = get_image_paths(row)\n    conditions = condition_mapping.get(row['series_description'], {})\n    if isinstance(conditions, str):  # Single condition\n        conditions = {'left': conditions, 'right': conditions}\n    for side, condition in conditions.items():\n        for image_path in image_paths:\n            expanded_rows.append({\n                'study_id': row['study_id'],\n                'series_id': row['series_id'],\n                'series_description': row['series_description'],\n                'image_path': image_path,\n                'condition': condition,\n                'row_id': f\"{row['study_id']}_{condition}\"\n            })\n\n# Create a new dataframe from the expanded rows\nexpanded_test_desc = pd.DataFrame(expanded_rows)\n\n# Display the resulting dataframe\nexpanded_test_desc.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:54:49.804156Z","iopub.execute_input":"2024-06-25T14:54:49.805282Z","iopub.status.idle":"2024-06-25T14:54:49.988254Z","shell.execute_reply.started":"2024-06-25T14:54:49.805241Z","shell.execute_reply":"2024-06-25T14:54:49.986741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# change severity column labels\n#Normal/Mild': 'normal_mild', 'Moderate': 'moderate', 'Severe': 'severe'}\nfinal_merged_df['severity'] = final_merged_df['severity'].map({'Normal/Mild': 'normal_mild', 'Moderate': 'moderate', 'Severe': 'severe'})","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:55:13.348787Z","iopub.execute_input":"2024-06-25T14:55:13.349285Z","iopub.status.idle":"2024-06-25T14:55:13.365490Z","shell.execute_reply.started":"2024-06-25T14:55:13.349250Z","shell.execute_reply":"2024-06-25T14:55:13.363751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = expanded_test_desc\ntrain_data = final_merged_df","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:55:20.980048Z","iopub.execute_input":"2024-06-25T14:55:20.980493Z","iopub.status.idle":"2024-06-25T14:55:20.986076Z","shell.execute_reply.started":"2024-06-25T14:55:20.980459Z","shell.execute_reply":"2024-06-25T14:55:20.984689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n# Define a function to check if a path exists\ndef check_exists(path):\n    return os.path.exists(path)\n\n# Define a function to check if a study ID directory exists\ndef check_study_id(row):\n    study_id = row['study_id']\n    path = f'{train_path}/train_images/{study_id}'\n    return check_exists(path)\n\n# Define a function to check if a series ID directory exists\ndef check_series_id(row):\n    study_id = row['study_id']\n    series_id = row['series_id']\n    path = f'{train_path}/train_images/{study_id}/{series_id}'\n    return check_exists(path)\n\n# Define a function to check if an image file exists\ndef check_image_exists(row):\n    image_path = row['image_path']\n    return check_exists(image_path)\n\n# Apply the functions to the train_data dataframe\ntrain_data['study_id_exists'] = train_data.apply(check_study_id, axis=1)\ntrain_data['series_id_exists'] = train_data.apply(check_series_id, axis=1)\ntrain_data['image_exists'] = train_data.apply(check_image_exists, axis=1)\n\n# Filter train_data\ntrain_data = train_data[(train_data['study_id_exists']) & (train_data['series_id_exists']) & (train_data['image_exists'])]","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:55:41.363845Z","iopub.execute_input":"2024-06-25T14:55:41.364306Z","iopub.status.idle":"2024-06-25T14:56:05.675248Z","shell.execute_reply.started":"2024-06-25T14:55:41.364273Z","shell.execute_reply":"2024-06-25T14:56:05.673948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:56:18.634992Z","iopub.execute_input":"2024-06-25T14:56:18.636281Z","iopub.status.idle":"2024-06-25T14:56:18.656257Z","shell.execute_reply.started":"2024-06-25T14:56:18.636238Z","shell.execute_reply":"2024-06-25T14:56:18.654988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom(path):\n    dicom = pydicom.read_file(path)\n    data = dicom.pixel_array\n    data = data - np.min(data)\n    if np.max(data) != 0:\n        data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    return data","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:56:36.756649Z","iopub.execute_input":"2024-06-25T14:56:36.757267Z","iopub.status.idle":"2024-06-25T14:56:36.764842Z","shell.execute_reply.started":"2024-06-25T14:56:36.757215Z","shell.execute_reply":"2024-06-25T14:56:36.763509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load images randomly\nimport random\nimages = []\nrow_ids = []\nselected_indices = random.sample(range(len(train_data)), 2)\nfor i in selected_indices:\n    image = load_dicom(train_data['image_path'][i])\n    images.append(image)\n    row_ids.append(train_data['row_id'][i])\n\n# Plot images\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nfor i in range(2):\n    ax[i].imshow(images[i], cmap='gray')\n    ax[i].set_title(f'Row ID: {row_ids[i]}', fontsize=8)\n    ax[i].axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:56:56.685780Z","iopub.execute_input":"2024-06-25T14:56:56.686254Z","iopub.status.idle":"2024-06-25T14:56:57.214698Z","shell.execute_reply.started":"2024-06-25T14:56:56.686220Z","shell.execute_reply":"2024-06-25T14:56:57.213260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#for one hot encoding\n#train_data[['normal_mild', 'severe', 'moderate']] = train_data[['normal_mild', 'severe', 'moderate']].astype(int) ","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:58:16.251634Z","iopub.execute_input":"2024-06-25T14:58:16.252193Z","iopub.status.idle":"2024-06-25T14:58:16.259165Z","shell.execute_reply.started":"2024-06-25T14:58:16.252153Z","shell.execute_reply":"2024-06-25T14:58:16.257377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:58:25.556681Z","iopub.execute_input":"2024-06-25T14:58:25.557223Z","iopub.status.idle":"2024-06-25T14:58:25.586489Z","shell.execute_reply.started":"2024-06-25T14:58:25.557183Z","shell.execute_reply":"2024-06-25T14:58:25.585000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = train_data.dropna()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:58:52.630840Z","iopub.execute_input":"2024-06-25T14:58:52.631257Z","iopub.status.idle":"2024-06-25T14:58:52.680751Z","shell.execute_reply.started":"2024-06-25T14:58:52.631225Z","shell.execute_reply":"2024-06-25T14:58:52.679530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.transforms as transforms\nimport torch\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom tqdm import tqdm\n\n# Define a custom dataset class\nclass CustomDataset(Dataset):\n    def __init__(self, dataframe, transform=None):\n        self.dataframe = dataframe\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.dataframe)\n\n    def __getitem__(self, index):\n        image_path = self.dataframe['image_path'][index]\n        image = load_dicom(image_path)  # Define this function to load your DICOM images\n        label = self.dataframe['severity'][index]\n        \n        if self.transform:\n            image = self.transform(image)\n\n        return image, label\n\n# Function to create datasets and dataloaders for each series description\ndef create_datasets_and_loaders(df, series_description, transform, batch_size=8):\n    filtered_df = df[df['series_description'] == series_description]\n    \n    train_df, val_df = train_test_split(filtered_df, test_size=0.2, random_state=42)\n    train_df = train_df.reset_index(drop=True)\n    val_df = val_df.reset_index(drop=True)\n\n    train_dataset = CustomDataset(train_df, transform)\n    val_dataset = CustomDataset(val_df, transform)\n\n    trainloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n    valloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n    \n    return trainloader, valloader, len(train_df), len(val_df)\n\n# Define the transforms\ntransform = transforms.Compose([\n    transforms.Lambda(lambda x: (x * 255).astype(np.uint8)),  # Convert back to uint8 for PIL\n    transforms.ToPILImage(),\n    transforms.Resize((224, 224)),\n    transforms.Grayscale(num_output_channels=3),\n    transforms.ToTensor(),\n])\n\n# Create dataloaders for each series description\ndataloaders = {}\nlengths = {}\n\ntrainloader_t1, valloader_t1, len_train_t1, len_val_t1 = create_datasets_and_loaders(train_data, 'Sagittal T1', transform)\ntrainloader_t2, valloader_t2, len_train_t2, len_val_t2 = create_datasets_and_loaders(train_data, 'Axial T2', transform)\ntrainloader_t2stir, valloader_t2stir, len_train_t2stir, len_val_t2stir = create_datasets_and_loaders(train_data, 'Sagittal T2/STIR', transform)\n\ndataloaders['Sagittal T1'] = (trainloader_t1, valloader_t1)\ndataloaders['Axial T2'] = (trainloader_t2, valloader_t2)\ndataloaders['Sagittal T2/STIR'] = (trainloader_t2stir, valloader_t2stir)\n\nlengths['Sagittal T1'] = (len_train_t1, len_val_t1)\nlengths['Axial T2'] = (len_train_t2, len_val_t2)\nlengths['Sagittal T2/STIR'] = (len_train_t2stir, len_val_t2stir)\n\n# Dictionary mapping labels to indices\nlabel_map = {'Mild': 0, 'Moderate': 1, 'Severe': 2}","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:59:36.964377Z","iopub.execute_input":"2024-06-25T14:59:36.964847Z","iopub.status.idle":"2024-06-25T14:59:39.294830Z","shell.execute_reply.started":"2024-06-25T14:59:36.964812Z","shell.execute_reply":"2024-06-25T14:59:39.293244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Function to visualize a batch of images\ndef visualize_batch(dataloader):\n    images, labels = next(iter(dataloader))\n    fig, axes = plt.subplots(1, len(images), figsize=(20, 5))\n    for i, (img, lbl) in enumerate(zip(images, labels)):\n        ax = axes[i]\n        img = img.permute(1, 2, 0)  # Convert to HWC for visualization\n        ax.imshow(img)\n        ax.set_title(f\"Label: {lbl}\")\n        ax.axis('off')\n    plt.show()\n\n# Visualize samples from each dataloader\nprint(\"Visualizing Sagittal T1 samples\")\nvisualize_batch(trainloader_t1)\nprint(\"Visualizing Axial T2 samples\")\nvisualize_batch(trainloader_t2)\nprint(\"Visualizing Sagittal T2/STIR samples\")\nvisualize_batch(trainloader_t2stir)","metadata":{"execution":{"iopub.status.busy":"2024-06-25T14:59:56.108331Z","iopub.execute_input":"2024-06-25T14:59:56.109155Z","iopub.status.idle":"2024-06-25T14:59:59.974579Z","shell.execute_reply.started":"2024-06-25T14:59:56.109083Z","shell.execute_reply":"2024-06-25T14:59:59.972951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nimage, label = next(iter(trainloader_t2))\nsample = image[1].permute(1, 2, 0)  #sample\n\n# Plot images\nplt.figsize=(8, 4)\nplt.imshow(images[0], cmap='gray')\nplt.title(label[0])\nplt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-25T15:00:17.155717Z","iopub.execute_input":"2024-06-25T15:00:17.156325Z","iopub.status.idle":"2024-06-25T15:00:17.703246Z","shell.execute_reply.started":"2024-06-25T15:00:17.156282Z","shell.execute_reply":"2024-06-25T15:00:17.701701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom tqdm import tqdm\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")","metadata":{"execution":{"iopub.status.busy":"2024-06-25T15:01:42.547938Z","iopub.execute_input":"2024-06-25T15:01:42.548388Z","iopub.status.idle":"2024-06-25T15:01:42.558278Z","shell.execute_reply.started":"2024-06-25T15:01:42.548354Z","shell.execute_reply":"2024-06-25T15:01:42.556376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\n\nclass CustomEfficientNetV2(nn.Module):\n    def __init__(self, num_classes=3, pretrained_weights=None):\n        super(CustomEfficientNetV2, self).__init__()\n        self.model = models.efficientnet_v2_s(weights=None)\n        if pretrained_weights:\n            self.model.load_state_dict(torch.load(pretrained_weights))\n        num_ftrs = self.model.classifier[-1].in_features\n        self.model.classifier[-1] = nn.Linear(num_ftrs, num_classes)\n\n    def forward(self, x):\n        return self.model(x)\n\n    def unfreeze_model(self):\n        # Unfreeze the last 20 layers, keeping BatchNorm layers frozen\n        for layer in list(self.model.features.children())[-20:]:\n            if not isinstance(layer, nn.BatchNorm2d):\n                for param in layer.parameters():\n                    param.requires_grad = True\n        \n        # Unfreeze the classifier\n        for param in self.model.classifier.parameters():\n            param.requires_grad = True\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# Path to the locally uploaded weights file\nweights_path = '/kaggle/input/efficientnetv2/pytorch/efficientnetv2s/1/efficientnet_v2_s-dd5fe13b.pth'\n\n# Initialize models\nsagittal_t1_model = CustomEfficientNetV2(num_classes=3, pretrained_weights=weights_path).to(device)\naxial_t2_model = CustomEfficientNetV2(num_classes=3, pretrained_weights=weights_path).to(device)\nsagittal_t2stir_model = CustomEfficientNetV2(num_classes=3, pretrained_weights=weights_path).to(device)\n\n# Optionally freeze initial layers\nfor param in sagittal_t1_model.model.features.parameters():\n    param.requires_grad = False\nfor param in axial_t2_model.model.features.parameters():\n    param.requires_grad = False\nfor param in sagittal_t2stir_model.model.features.parameters():\n    param.requires_grad = False\n\n# Unfreeze the final fully connected layer\nfor param in sagittal_t1_model.model.classifier.parameters():\n    param.requires_grad = True\nfor param in axial_t2_model.model.classifier.parameters():\n    param.requires_grad = True\nfor param in sagittal_t2stir_model.model.classifier.parameters():\n    param.requires_grad = True\n\n# Training parameters\ncriterion = nn.CrossEntropyLoss()\n\n# Initialize separate optimizers for each model\noptimizer_sagittal_t1 = torch.optim.Adam(sagittal_t1_model.model.classifier.parameters(), lr=0.001)\noptimizer_axial_t2 = torch.optim.Adam(axial_t2_model.model.classifier.parameters(), lr=0.001)\noptimizer_sagittal_t2stir = torch.optim.Adam(sagittal_t2stir_model.model.classifier.parameters(), lr=0.001)\n\n# Store the models and optimizers in dictionaries for easy access\nmodels = {\n    'Sagittal T1': sagittal_t1_model,\n    'Axial T2': axial_t2_model,\n    'Sagittal T2/STIR': sagittal_t2stir_model,\n}\noptimizers = {\n    'Sagittal T1': optimizer_sagittal_t1,\n    'Axial T2': optimizer_axial_t2,\n    'Sagittal T2/STIR': optimizer_sagittal_t2stir,\n}","metadata":{"execution":{"iopub.status.busy":"2024-06-25T15:01:44.380712Z","iopub.execute_input":"2024-06-25T15:01:44.381225Z","iopub.status.idle":"2024-06-25T15:01:45.129517Z","shell.execute_reply.started":"2024-06-25T15:01:44.381189Z","shell.execute_reply":"2024-06-25T15:01:45.126209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}