{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":71549,"databundleVersionId":8561470,"sourceType":"competition"},{"sourceId":992,"sourceType":"modelInstanceVersion","modelInstanceId":846,"modelId":101}],"dockerImageVersionId":30805,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\ncounter = 0  # Sayaç başlat\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        counter += 1\n        if counter == 15:  # 5 dosya yazdırdıktan sonra dur\n            break\n    if counter == 15:  # İç döngü kırıldığında dış döngüyü de kır\n        break\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":"2024-12-18T21:22:26.538682Z","iopub.execute_input":"2024-12-18T21:22:26.539044Z","iopub.status.idle":"2024-12-18T21:22:27.090442Z","shell.execute_reply.started":"2024-12-18T21:22:26.539011Z","shell.execute_reply":"2024-12-18T21:22:27.089588Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We are preparing this notebook to prepare the dataset before the training era. We were inspired from these notebooks: https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-making-dataset/notebook https://www.kaggle.com/code/itsuki9180/rsna2024-lsdc-making-dataset I think creating a new row_id for test and train cvs files is best approach to use dicom files in a easy way. Its too complicated pulling rows from different csv files for one dicom image. We didnt decided yet but we probably convert these dicom images to png and use this notebook output as a input for our model notebook.","metadata":{}},{"cell_type":"code","source":"import cv2\nimport time\nimport glob\nimport json\nimport torch\nimport collections\nimport seaborn as sns\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport pydicom as dicom\nimport albumentations as A\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport torchvision.models as models\nimport matplotlib.patches as patches\nfrom matplotlib import animation, rc\nimport torchvision.transforms as transforms\nfrom albumentations.pytorch import ToTensorV2\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.092090Z","iopub.execute_input":"2024-12-18T21:22:27.092742Z","iopub.status.idle":"2024-12-18T21:22:27.098273Z","shell.execute_reply.started":"2024-12-18T21:22:27.092701Z","shell.execute_reply":"2024-12-18T21:22:27.097220Z"}},"outputs":[],"execution_count":null},{"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')\nlen(test_desc) #number of test_description.csv rows ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.099334Z","iopub.execute_input":"2024-12-18T21:22:27.099884Z","iopub.status.idle":"2024-12-18T21:22:27.182694Z","shell.execute_reply.started":"2024-12-18T21:22:27.099845Z","shell.execute_reply":"2024-12-18T21:22:27.181856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_desc.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.184890Z","iopub.execute_input":"2024-12-18T21:22:27.185495Z","iopub.status.idle":"2024-12-18T21:22:27.192934Z","shell.execute_reply.started":"2024-12-18T21:22:27.185456Z","shell.execute_reply":"2024-12-18T21:22:27.192130Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.194114Z","iopub.execute_input":"2024-12-18T21:22:27.194460Z","iopub.status.idle":"2024-12-18T21:22:27.211879Z","shell.execute_reply.started":"2024-12-18T21:22:27.194422Z","shell.execute_reply":"2024-12-18T21:22:27.211118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_desc.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.213189Z","iopub.execute_input":"2024-12-18T21:22:27.213434Z","iopub.status.idle":"2024-12-18T21:22:27.223288Z","shell.execute_reply.started":"2024-12-18T21:22:27.213410Z","shell.execute_reply":"2024-12-18T21:22:27.222424Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:27.224337Z","iopub.execute_input":"2024-12-18T21:22:27.224564Z","iopub.status.idle":"2024-12-18T21:22:30.291964Z","shell.execute_reply.started":"2024-12-18T21:22:27.224540Z","shell.execute_reply":"2024-12-18T21:22:30.291266Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_desc)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:30.293092Z","iopub.execute_input":"2024-12-18T21:22:30.293755Z","iopub.status.idle":"2024-12-18T21:22:30.299389Z","shell.execute_reply.started":"2024-12-18T21:22:30.293716Z","shell.execute_reply":"2024-12-18T21:22:30.298465Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_image_paths)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:30.300311Z","iopub.execute_input":"2024-12-18T21:22:30.300545Z","iopub.status.idle":"2024-12-18T21:22:30.308685Z","shell.execute_reply.started":"2024-12-18T21:22:30.300517Z","shell.execute_reply":"2024-12-18T21:22:30.307858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define function to reshape a single row of the DataFrame\ndef reshape_row(row):\n    data = {'study_id': [], 'condition': [], 'level': [], 'severity': []}\n    \n    for column, value in row.items():\n        if column not in ['study_id', 'series_id', 'instance_number', 'x', 'y', 'series_description']:\n            parts = column.split('_')\n            condition = ' '.join([word.capitalize() for word in parts[:-2]])\n            level = parts[-2].capitalize() + '/' + parts[-1].capitalize()\n            data['study_id'].append(row['study_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_train_df = pd.concat([reshape_row(row) for _, row in train.iterrows()], ignore_index=True)\n\n# Display the first few rows of the reshaped dataframe\nnew_train_df.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:30.311333Z","iopub.execute_input":"2024-12-18T21:22:30.311623Z","iopub.status.idle":"2024-12-18T21:22:31.167659Z","shell.execute_reply.started":"2024-12-18T21:22:30.311598Z","shell.execute_reply":"2024-12-18T21:22:31.166798Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.168679Z","iopub.execute_input":"2024-12-18T21:22:31.168926Z","iopub.status.idle":"2024-12-18T21:22:31.174324Z","shell.execute_reply.started":"2024-12-18T21:22:31.168900Z","shell.execute_reply":"2024-12-18T21:22:31.173408Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.175522Z","iopub.execute_input":"2024-12-18T21:22:31.175902Z","iopub.status.idle":"2024-12-18T21:22:31.224930Z","shell.execute_reply.started":"2024-12-18T21:22:31.175864Z","shell.execute_reply":"2024-12-18T21:22:31.224104Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.225969Z","iopub.execute_input":"2024-12-18T21:22:31.226211Z","iopub.status.idle":"2024-12-18T21:22:31.244933Z","shell.execute_reply.started":"2024-12-18T21:22:31.226188Z","shell.execute_reply":"2024-12-18T21:22:31.244079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.245871Z","iopub.execute_input":"2024-12-18T21:22:31.246157Z","iopub.status.idle":"2024-12-18T21:22:31.387635Z","shell.execute_reply.started":"2024-12-18T21:22:31.246131Z","shell.execute_reply":"2024-12-18T21:22:31.386582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Normal/Mild\"].value_counts().sum()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.388596Z","iopub.execute_input":"2024-12-18T21:22:31.388842Z","iopub.status.idle":"2024-12-18T21:22:31.489026Z","shell.execute_reply.started":"2024-12-18T21:22:31.388818Z","shell.execute_reply":"2024-12-18T21:22:31.488220Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Moderate\"].value_counts().sum()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.490442Z","iopub.execute_input":"2024-12-18T21:22:31.490979Z","iopub.status.idle":"2024-12-18T21:22:31.523850Z","shell.execute_reply.started":"2024-12-18T21:22:31.490921Z","shell.execute_reply":"2024-12-18T21:22:31.523062Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.524856Z","iopub.execute_input":"2024-12-18T21:22:31.525131Z","iopub.status.idle":"2024-12-18T21:22:31.610805Z","shell.execute_reply.started":"2024-12-18T21:22:31.525104Z","shell.execute_reply":"2024-12-18T21:22:31.610065Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.611759Z","iopub.execute_input":"2024-12-18T21:22:31.612041Z","iopub.status.idle":"2024-12-18T21:22:31.619718Z","shell.execute_reply.started":"2024-12-18T21:22:31.612015Z","shell.execute_reply":"2024-12-18T21:22:31.618943Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data = expanded_test_desc\ntrain_data = final_merged_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.620749Z","iopub.execute_input":"2024-12-18T21:22:31.621052Z","iopub.status.idle":"2024-12-18T21:22:31.632828Z","shell.execute_reply.started":"2024-12-18T21:22:31.621027Z","shell.execute_reply":"2024-12-18T21:22:31.632165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:31.633664Z","iopub.execute_input":"2024-12-18T21:22:31.634008Z","iopub.status.idle":"2024-12-18T21:22:51.117680Z","shell.execute_reply.started":"2024-12-18T21:22:31.633976Z","shell.execute_reply":"2024-12-18T21:22:51.116706Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:51.118943Z","iopub.execute_input":"2024-12-18T21:22:51.119348Z","iopub.status.idle":"2024-12-18T21:22:51.132842Z","shell.execute_reply.started":"2024-12-18T21:22:51.119306Z","shell.execute_reply":"2024-12-18T21:22:51.131916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data['series_description'].value_counts()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:51.134141Z","iopub.execute_input":"2024-12-18T21:22:51.134403Z","iopub.status.idle":"2024-12-18T21:22:51.148681Z","shell.execute_reply.started":"2024-12-18T21:22:51.134377Z","shell.execute_reply":"2024-12-18T21:22:51.148011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_path = \"/kaggle/working/png_images\"\nif not os.path.exists(output_path): \n                os.makedirs(output_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:51.149683Z","iopub.execute_input":"2024-12-18T21:22:51.150025Z","iopub.status.idle":"2024-12-18T21:22:51.157857Z","shell.execute_reply.started":"2024-12-18T21:22:51.149989Z","shell.execute_reply":"2024-12-18T21:22:51.157223Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom(path):\n    dicomf = dicom.dcmread(path)\n    data = dicomf.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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:51.158705Z","iopub.execute_input":"2024-12-18T21:22:51.158932Z","iopub.status.idle":"2024-12-18T21:22:51.170505Z","shell.execute_reply.started":"2024-12-18T21:22:51.158908Z","shell.execute_reply":"2024-12-18T21:22:51.169665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_bounding_box(center_x, center_y, width, height):\n    # Bounding box'un sol üst köşesinin koordinatlarını hesapla\n    xmin = center_x - width // 2\n    ymin = center_y - height // 2\n    \n    # Bounding box'un sağ alt köşesinin koordinatlarını hesapla\n    xmax = center_x + width // 2\n    ymax = center_y + height // 2\n    \n    return int(xmin), int(ymin), int(xmax), int(ymax)\n\n\ndef draw_bounding_box(image, bbox, color=(255, 0, 0), thickness=2):\n    xmin, ymin, xmax, ymax = bbox\n    cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, thickness)\n    return image\n\n# bounding box boyutları\nbox_width = 100\nbox_height = 100\n\nbboxes = []\n\nfor index, row in train_data.iterrows(): \n    center_x = row['x'] \n    center_y = row['y'] \n    bbox = create_bounding_box(center_x, center_y, box_width, box_height) \n    bboxes.append(bbox)\nprint(\"checkpoint\")\ntrain_data['bounding_box'] = bboxes\nprint(\"5734. Bounding Box Koordinatları:\", bboxes[5734])\n\ncounter = 0\n# Her bir resim için bounding box'ları çizme \n#for index, row in train_data.iterrows(): \n    #image_path = row['image_path'] \n    #bbox = bboxes[index]  \n    #image = load_dicom(image_path) \n    #image_with_bbox = draw_bounding_box(image, bbox)  \n    # Görüntüyü PNG olarak kaydetme\n    #output_file = os.path.join(output_path, f\"{row['row_id']}.png\") \n    #cv2.imwrite(output_file, image_with_bbox) \n    #print(f\"Saved: {output_file}\")\n    #plt.imshow(image_with_bbox, cmap='gray')\n    #plt.show() #plt.imshow sadece görüntüyü hazırlarmış, görüntülemezmiş.\n    #counter += 1\n    #if counter == 3:\n     #   break\n#plt.imshow(image_with_bbox, cmap='gray')\n#plt.show \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T21:22:51.171617Z","iopub.execute_input":"2024-12-18T21:22:51.172155Z","iopub.status.idle":"2024-12-18T21:22:53.236428Z","shell.execute_reply.started":"2024-12-18T21:22:51.172128Z","shell.execute_reply":"2024-12-18T21:22:53.235491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn.functional as F\n\ndef custom_collate_fn(batch):\n    images, labels, bboxes = zip(*batch)\n    \n    # Maksimum boyutu bul\n    max_height = max([img.shape[1] for img in images])\n    max_width = max([img.shape[2] for img in images])\n\n    # Görüntüleri pad ile hizala\n    padded_images = [\n        F.pad(img, (0, max_width - img.shape[2], 0, max_height - img.shape[1]))\n        for img in images\n    ]\n    \n    return torch.stack(padded_images), labels, bboxes\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T22:25:49.037300Z","iopub.execute_input":"2024-12-18T22:25:49.037671Z","iopub.status.idle":"2024-12-18T22:25:49.043921Z","shell.execute_reply.started":"2024-12-18T22:25:49.037640Z","shell.execute_reply":"2024-12-18T22:25:49.042825Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define a custom dataset class\nclass CustomDataset(Dataset):\n    def __init__(self, dataframe, bboxes, 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        bounding_box = self.dataframe['bounding_box'][index]\n        \n\n        \n        if self.transform:\n            transformed = self.transform(image=image, bboxes=[bounding_box], category_ids=[label])\n            image = transformed['image']\n            bounding_box = transformed['bboxes'][0]\n        \n        #if self.transform:\n         #   image = self.transform(image)\n       \n        return image, label, bounding_box\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# 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    # frac değerini değiştirerek trainde verinin ne kadarını kullanacagını belirlersin\n    filtered_df = filtered_df.sample(frac=1.0, random_state=42)  \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, collate_fn=custom_collate_fn)\n    valloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n    \n    return trainloader, valloader, len(train_df), len(val_df)\n\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\"\"\"\ntransform = A.Compose([\n    A.HorizontalFlip(p=0.5),\n    A.Rotate(limit=30),\n    A.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1),\n    A.RandomResizedCrop(height=224, width=224, scale=(0.8, 1.0)),\n    A.RandomSizedBBoxSafeCrop(height=224, width=224, erosion_rate=0.0),\n    A.Resize(height=224, width=224),\n    ToTensorV2() \n], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['category_ids']))\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}\nprint(\"oldu galiba?\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T22:44:17.457242Z","iopub.execute_input":"2024-12-18T22:44:17.457604Z","iopub.status.idle":"2024-12-18T22:44:17.519977Z","shell.execute_reply.started":"2024-12-18T22:44:17.457572Z","shell.execute_reply":"2024-12-18T22:44:17.518965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T22:44:22.792139Z","iopub.execute_input":"2024-12-18T22:44:22.792482Z","iopub.status.idle":"2024-12-18T22:44:22.811746Z","shell.execute_reply.started":"2024-12-18T22:44:22.792449Z","shell.execute_reply":"2024-12-18T22:44:22.810802Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data = train_data.dropna()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T22:36:39.055381Z","iopub.execute_input":"2024-12-18T22:36:39.055738Z","iopub.status.idle":"2024-12-18T22:36:39.082791Z","shell.execute_reply.started":"2024-12-18T22:36:39.055703Z","shell.execute_reply":"2024-12-18T22:36:39.081858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Function to visualize a batch of images\n\"\"\"def 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    \"\"\"\ndef visualize_batch(dataloader):\n    batch = next(iter(dataloader))\n    images, labels, bboxes = zip(*batch)\n    fig, axes = plt.subplots(1, len(images), figsize=(20, 5))\n    for i, (img, lbl, bbox) in enumerate(zip(images, labels, bboxes)):\n        axes[i].imshow(img.permute(1, 2, 0))\n        rect = patches.Rectangle((bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1], linewidth=1, edgecolor='r', facecolor='none')\n        axes[i].add_patch(rect)\n        axes[i].set_title(f'Label: {lbl}')\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-18T22:36:41.272841Z","iopub.execute_input":"2024-12-18T22:36:41.273780Z","iopub.status.idle":"2024-12-18T22:36:41.564375Z","shell.execute_reply.started":"2024-12-18T22:36:41.273731Z","shell.execute_reply":"2024-12-18T22:36:41.563148Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image, 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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:37.635228Z","iopub.execute_input":"2024-12-08T21:16:37.635498Z","iopub.status.idle":"2024-12-08T21:16:38.184335Z","shell.execute_reply.started":"2024-12-08T21:16:37.63547Z","shell.execute_reply":"2024-12-08T21:16:38.183514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass CustomResNet50(nn.Module):\n    def __init__(self, num_classes=3, pretrained_weights=None):\n        super(CustomResNet50, self).__init__()\n        # pretrained=False ile modelin rastgele ağırlıklarla başlatılmasını sağla\n        self.model = models.resnet50(pretrained=False)\n        \n        # Eğer manuel ağırlık yolu verilmişse, bu ağırlıkları yükle\n        if pretrained_weights:\n            self.model.load_state_dict(torch.load(pretrained_weights))\n        \n        num_ftrs = self.model.fc.in_features  # Son katmanın özellik sayısını al\n        self.model.fc = nn.Linear(num_ftrs, num_classes)  # Son katmanı değiştir\n\n    def forward(self, x):\n        return self.model(x)\n\n    def unfreeze_model(self):\n        \"\"\"Tüm katmanları çöz.\"\"\"\n        for param in self.model.parameters():\n            param.requires_grad = True\n\n    def unfreeze_specific_layers(self, layer_names=None):\n        \"\"\"\n        Belirli katmanları çözmek için kullanılabilir.\n        Eğer layer_names None ise, tüm katmanlar çözülür.\n        \"\"\"\n        for name, param in self.model.named_parameters():\n            if layer_names is None or any(layer in name for layer in layer_names):\n                param.requires_grad = True\n            else:\n                param.requires_grad = False\n\n# Cihaz seçimi\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Modeli başlat\nsagittal_t1_model = CustomResNet50(num_classes=3).to(device)\naxial_t2_model = CustomResNet50(num_classes=3).to(device)\nsagittal_t2stir_model = CustomResNet50(num_classes=3).to(device)\n\n\"\"\"# Son fully connected katmanı çözme\nfor param in sagittal_t1_model.model.fc.parameters():\n    param.requires_grad = True\nfor param in axial_t2_model.model.fc.parameters():\n    param.requires_grad = True\nfor param in sagittal_t2stir_model.model.fc.parameters():\n    param.requires_grad = True\n\n# Başlangıç katmanlarını dondurma\nfor param in sagittal_t1_model.model.parameters():\n    if param is not sagittal_t1_model.model.fc.weight and param is not sagittal_t1_model.model.fc.bias:\n        param.requires_grad = False\n\nfor param in axial_t2_model.model.parameters():\n    if param is not axial_t2_model.model.fc.weight and param is not axial_t2_model.model.fc.bias:\n        param.requires_grad = False\n\nfor param in sagittal_t2stir_model.model.parameters():\n    if param is not sagittal_t2stir_model.model.fc.weight and param is not sagittal_t2stir_model.model.fc.bias:\n        param.requires_grad = False\n\n# Eğitim parametreleri\ncriterion = nn.CrossEntropyLoss()\"\"\"\n# Tüm katmanları çözmek için\nfor model in [sagittal_t1_model, axial_t2_model, sagittal_t2stir_model]:\n    model.unfreeze_model()  # Bütün katmanları çöz\n\n# Eğitim parametreleri 05.12.2024 saat 0423'de güncellendi.\nweights = torch.tensor([1.0, 2.0, 4.0])\ncriterion = nn.CrossEntropyLoss(weight=weights.to(device))\n\n# Optimizer ayarları\noptimizer_sagittal_t1 = torch.optim.Adam(sagittal_t1_model.model.fc.parameters(), lr=0.001)\noptimizer_axial_t2 = torch.optim.Adam(axial_t2_model.model.fc.parameters(), lr=0.001)\noptimizer_sagittal_t2stir = torch.optim.Adam(sagittal_t2stir_model.model.fc.parameters(), lr=0.001)\n\n# Modelleri ve optimizörleri saklamak için dictionary\nmodels = {\n    'Sagittal T1': sagittal_t1_model,\n    'Axial T2': axial_t2_model,\n    'Sagittal T2/STIR': sagittal_t2stir_model,\n}\n\noptimizers = {\n    'Sagittal T1': optimizer_sagittal_t1,\n    'Axial T2': optimizer_axial_t2,\n    'Sagittal T2/STIR': optimizer_sagittal_t2stir,\n}\n\n\n# Eğitim yapılabilir parametrelerin sayısını yazdır\nfor model_name, model in models.items():\n    trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    print(f\"Trainable parameters for {model_name}: {trainable_params}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:38.192989Z","iopub.execute_input":"2024-12-08T21:16:38.193248Z","iopub.status.idle":"2024-12-08T21:16:39.822921Z","shell.execute_reply.started":"2024-12-08T21:16:38.193224Z","shell.execute_reply":"2024-12-08T21:16:39.822048Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_map = {'normal_mild': 0, 'moderate': 1, 'severe': 2}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:39.823964Z","iopub.execute_input":"2024-12-08T21:16:39.824217Z","iopub.status.idle":"2024-12-08T21:16:39.828112Z","shell.execute_reply.started":"2024-12-08T21:16:39.824192Z","shell.execute_reply":"2024-12-08T21:16:39.827254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for images, labels in trainloader_t2:\n    labels = torch.tensor([label_map[label] for label in labels])\n    labels = labels.to(device)\n    print(labels)\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:39.829045Z","iopub.execute_input":"2024-12-08T21:16:39.829278Z","iopub.status.idle":"2024-12-08T21:16:39.958563Z","shell.execute_reply.started":"2024-12-08T21:16:39.829256Z","shell.execute_reply":"2024-12-08T21:16:39.957674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_model(model, trainloader, valloader, len_train, len_val, optimizer, num_epochs=10, patience=3):\n    # Learning rate scheduler\n    scheduler = lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.1)\n    \n    best_val_acc = 0.0\n    best_model_wts = deepcopy(model.state_dict())\n    counter = 0\n    \n    for epoch in range(num_epochs):\n        model.train()\n        train_loss = 0\n        correct_train = 0\n        \n        with tqdm(trainloader, unit=\"batch\") as tepoch:\n            for images, labels in tepoch:\n                images, labels = images.to(device), torch.tensor([label_map[label] for label in labels]).to(device)\n                optimizer.zero_grad()\n                outputs = model(images)\n                loss = criterion(outputs, labels)\n                loss.backward()\n                optimizer.step()\n                train_loss += loss.item()\n                \n                probabilities = torch.softmax(outputs, dim=1)\n                _, predicted = torch.max(probabilities, 1)\n                correct_train += (predicted == labels).sum().item()\n                \n                tepoch.set_postfix(epoch=epoch+1)\n        \n        scheduler.step()\n        \n        train_loss /= len(trainloader)\n        train_acc = 100 * correct_train / len_train\n        \n        model.eval()\n        val_loss, correct_val = 0, 0\n        with torch.no_grad():\n            with tqdm(valloader, unit=\"batch\") as vepoch:\n                for images, labels in vepoch:\n                    images, labels = images.to(device), torch.tensor([label_map[label] for label in labels]).to(device)\n                    outputs = model(images)\n                    loss = criterion(outputs, labels)\n                    val_loss += loss.item()\n                    \n                    probabilities = torch.softmax(outputs, dim=1)\n\n                    # Eğer batch size 1 ise, dim=0 kullanarak doğru boyutta işlem yapabilirsiniz\n                    if probabilities.dim() == 1:\n                        _, predicted = torch.max(probabilities, 0)  # batch size 1 ise dim=0\n                    else:\n                        _, predicted = torch.max(probabilities, 1)  # normal durumda dim=1\n                    correct_val += (predicted == labels).sum().item()\n                    \n                    vepoch.set_postfix(epoch=epoch+1)\n        \n        val_loss /= len(valloader)\n        val_acc = 100 * correct_val / len_val\n        \n        print(f\"Epoch {epoch+1}, Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.2f}%, Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.2f}%\")\n        \n        # Save the best model and check for early stopping\n        if val_acc > best_val_acc:\n            best_val_acc = val_acc\n            best_model_wts = deepcopy(model.state_dict())\n            counter = 0\n            torch.save(best_model_wts, f'best_model_{epoch+1}.pth')\n        else:\n            counter += 1\n        \n        # Early stopping\n        if counter >= patience:\n            print(f\"Early stopping triggered after {epoch+1} epochs\")\n            break\n    \n    # Load best model weights\n    model.load_state_dict(best_model_wts)\n    return model, best_val_acc","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:39.959578Z","iopub.execute_input":"2024-12-08T21:16:39.959863Z","iopub.status.idle":"2024-12-08T21:16:39.971166Z","shell.execute_reply.started":"2024-12-08T21:16:39.959838Z","shell.execute_reply":"2024-12-08T21:16:39.970479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Training all models\nfor desc, model in models.items():\n    if desc == 'Sagittal T1':\n        trainloader, valloader, len_train, len_val = trainloader_t1, valloader_t1, len_train_t1, len_val_t1\n    elif desc == 'Axial T2':\n        trainloader, valloader, len_train, len_val = trainloader_t2, valloader_t2, len_train_t2, len_val_t2\n    elif desc == 'Sagittal T2/STIR':\n        trainloader, valloader, len_train, len_val = trainloader_t2stir, valloader_t2stir, len_train_t2stir, len_val_t2stir\n    \n    print(f\"Training model for {desc}\")\n    train_model(model, trainloader, valloader, len_train, len_val, optimizers[desc])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T21:16:39.971897Z","iopub.execute_input":"2024-12-08T21:16:39.972162Z","iopub.status.idle":"2024-12-08T22:14:31.819436Z","shell.execute_reply.started":"2024-12-08T21:16:39.972135Z","shell.execute_reply":"2024-12-08T22:14:31.818519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data['level'].unique()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.820878Z","iopub.execute_input":"2024-12-08T22:14:31.821466Z","iopub.status.idle":"2024-12-08T22:14:31.831116Z","shell.execute_reply.started":"2024-12-08T22:14:31.821425Z","shell.execute_reply":"2024-12-08T22:14:31.830357Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"expanded_test_desc.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.832147Z","iopub.execute_input":"2024-12-08T22:14:31.832451Z","iopub.status.idle":"2024-12-08T22:14:31.846328Z","shell.execute_reply.started":"2024-12-08T22:14:31.832426Z","shell.execute_reply":"2024-12-08T22:14:31.845526Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"levels = ['l1_l2', 'l2_l3', 'l3_l4', 'l4_l5', 'l5_s1']\n\n# Function to update row_id with levels\ndef update_row_id(row, levels):\n    level = levels[row.name % len(levels)]\n    return f\"{row['study_id']}_{row['condition']}_{level}\"\n\n# Update row_id in expanded_test_desc to include levels\nexpanded_test_desc['row_id'] = expanded_test_desc.apply(lambda row: update_row_id(row, levels), axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.847354Z","iopub.execute_input":"2024-12-08T22:14:31.847693Z","iopub.status.idle":"2024-12-08T22:14:31.864539Z","shell.execute_reply.started":"2024-12-08T22:14:31.847649Z","shell.execute_reply":"2024-12-08T22:14:31.863828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"expanded_test_desc.head(2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.865357Z","iopub.execute_input":"2024-12-08T22:14:31.865671Z","iopub.status.idle":"2024-12-08T22:14:31.879874Z","shell.execute_reply.started":"2024-12-08T22:14:31.865634Z","shell.execute_reply":"2024-12-08T22:14:31.879091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define a custom test dataset class\nclass TestDataset(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        if self.transform:\n            image = self.transform(image)\n        return image\n\n# Define the transforms\ntransform = transforms.Compose([\n    transforms.ToPILImage(),\n    transforms.Resize((224, 224)),\n    transforms.Grayscale(num_output_channels=3),\n    transforms.ToTensor(),\n])\n\n# Create a test dataset and dataloader\ntest_dataset = TestDataset(expanded_test_desc, transform)\ntestloader = DataLoader(test_dataset, batch_size=1, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.880893Z","iopub.execute_input":"2024-12-08T22:14:31.881154Z","iopub.status.idle":"2024-12-08T22:14:31.889539Z","shell.execute_reply.started":"2024-12-08T22:14:31.881127Z","shell.execute_reply":"2024-12-08T22:14:31.888668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for image in testloader:\n    print(image.shape)\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.890502Z","iopub.execute_input":"2024-12-08T22:14:31.891062Z","iopub.status.idle":"2024-12-08T22:14:31.920945Z","shell.execute_reply.started":"2024-12-08T22:14:31.891023Z","shell.execute_reply":"2024-12-08T22:14:31.92023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Function to get the model based on series_description\ndef get_model(series_description):\n    return models.get(series_description, None)\n\n# Function to make predictions on the test data\ndef predict_test_data(testloader, expanded_test_desc):\n    predictions = []\n    normal_mild_probs = []\n    moderate_probs = []\n    severe_probs = []\n    \n    for model in models.values():\n        model.eval()\n        \n    with torch.no_grad():\n        for idx, images in enumerate(tqdm(testloader)):\n            images = images.to(device)\n            series_description = expanded_test_desc.iloc[idx]['series_description']\n            model = get_model(series_description)\n            if model:\n                model.eval()  # Set the model to eval mode\n                outputs = model(images)\n                probs = torch.softmax(outputs, dim=1).squeeze(0)\n                normal_mild_probs.append(probs[0].item())\n                moderate_probs.append(probs[1].item())\n                severe_probs.append(probs[2].item())\n                predictions.append(probs)\n            else:\n                normal_mild_probs.append(None)\n                moderate_probs.append(None)\n                severe_probs.append(None)\n                predictions.append(None)\n    return normal_mild_probs, moderate_probs, severe_probs, predictions","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.921767Z","iopub.execute_input":"2024-12-08T22:14:31.922018Z","iopub.status.idle":"2024-12-08T22:14:31.930103Z","shell.execute_reply.started":"2024-12-08T22:14:31.921991Z","shell.execute_reply":"2024-12-08T22:14:31.929286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Make predictions on the test data\nnormal_mild_probs, moderate_probs, severe_probs, test_predictions = predict_test_data(testloader, expanded_test_desc)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:31.93113Z","iopub.execute_input":"2024-12-08T22:14:31.931394Z","iopub.status.idle":"2024-12-08T22:14:36.113313Z","shell.execute_reply.started":"2024-12-08T22:14:31.93137Z","shell.execute_reply":"2024-12-08T22:14:36.112448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_predictions[0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.114457Z","iopub.execute_input":"2024-12-08T22:14:36.114758Z","iopub.status.idle":"2024-12-08T22:14:36.121458Z","shell.execute_reply.started":"2024-12-08T22:14:36.114732Z","shell.execute_reply":"2024-12-08T22:14:36.120646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Add predictions and probabilities to the test DataFrame\nexpanded_test_desc['normal_mild'] = normal_mild_probs\nexpanded_test_desc['moderate'] = moderate_probs\nexpanded_test_desc['severe'] = severe_probs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.122787Z","iopub.execute_input":"2024-12-08T22:14:36.123089Z","iopub.status.idle":"2024-12-08T22:14:36.131635Z","shell.execute_reply.started":"2024-12-08T22:14:36.123061Z","shell.execute_reply":"2024-12-08T22:14:36.130791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = expanded_test_desc[[\"row_id\",\"normal_mild\",\"moderate\",\"severe\"]]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.132703Z","iopub.execute_input":"2024-12-08T22:14:36.132975Z","iopub.status.idle":"2024-12-08T22:14:36.142696Z","shell.execute_reply.started":"2024-12-08T22:14:36.132947Z","shell.execute_reply":"2024-12-08T22:14:36.14196Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.143709Z","iopub.execute_input":"2024-12-08T22:14:36.144Z","iopub.status.idle":"2024-12-08T22:14:36.160824Z","shell.execute_reply.started":"2024-12-08T22:14:36.143974Z","shell.execute_reply":"2024-12-08T22:14:36.160032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Group by 'row_id' and sum the values\ngrouped_submission = submission.groupby('row_id').max().reset_index()\n\n# Normalize the columns\ngrouped_submission[['normal_mild', 'moderate', 'severe']] = grouped_submission[['normal_mild', 'moderate', 'severe']].div(grouped_submission[['normal_mild', 'moderate', 'severe']].sum(axis=1), axis=0)\n\n# Check the first 3 rows\ngrouped_submission","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.161785Z","iopub.execute_input":"2024-12-08T22:14:36.162048Z","iopub.status.idle":"2024-12-08T22:14:36.183948Z","shell.execute_reply.started":"2024-12-08T22:14:36.162021Z","shell.execute_reply":"2024-12-08T22:14:36.183116Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(grouped_submission)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.18491Z","iopub.execute_input":"2024-12-08T22:14:36.185221Z","iopub.status.idle":"2024-12-08T22:14:36.196469Z","shell.execute_reply.started":"2024-12-08T22:14:36.185175Z","shell.execute_reply":"2024-12-08T22:14:36.195685Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub[['normal_mild', 'moderate', 'severe']] = grouped_submission[['normal_mild', 'moderate', 'severe']]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.197443Z","iopub.execute_input":"2024-12-08T22:14:36.197767Z","iopub.status.idle":"2024-12-08T22:14:36.207567Z","shell.execute_reply.started":"2024-12-08T22:14:36.197732Z","shell.execute_reply":"2024-12-08T22:14:36.20683Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the DataFrame to \"submission.csv\" in the desired directory\nsub.to_csv(\"/kaggle/working/submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.208588Z","iopub.execute_input":"2024-12-08T22:14:36.208951Z","iopub.status.idle":"2024-12-08T22:14:36.219663Z","shell.execute_reply.started":"2024-12-08T22:14:36.208916Z","shell.execute_reply":"2024-12-08T22:14:36.21894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T22:14:36.220545Z","iopub.execute_input":"2024-12-08T22:14:36.220911Z","iopub.status.idle":"2024-12-08T22:14:36.233746Z","shell.execute_reply.started":"2024-12-08T22:14:36.220882Z","shell.execute_reply":"2024-12-08T22:14:36.232918Z"}},"outputs":[],"execution_count":null}]}