{"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":30804,"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\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":"a2af06e8-7494-4b59-ac02-4d913f17ae8a","_cell_guid":"33087906-fdd6-403a-b527-eb53db597b83","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.332644Z","iopub.execute_input":"2024-12-08T19:55:15.333008Z","iopub.status.idle":"2024-12-08T19:55:15.809319Z","shell.execute_reply.started":"2024-12-08T19:55:15.332976Z","shell.execute_reply":"2024-12-08T19:55:15.80853Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"574ad83d-1711-4d78-bd16-b23a55eff284","_cell_guid":"11ef6446-ced4-44e2-9a85-21e3619fcdce","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.811114Z","iopub.execute_input":"2024-12-08T19:55:15.811717Z","iopub.status.idle":"2024-12-08T19:55:15.816772Z","shell.execute_reply.started":"2024-12-08T19:55:15.811678Z","shell.execute_reply":"2024-12-08T19:55:15.815927Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"450f1641-420f-454f-b98c-c27f0b17b9c6","_cell_guid":"570d0a9c-a959-4d61-81b7-da90ab7da4fb","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.817647Z","iopub.execute_input":"2024-12-08T19:55:15.817955Z","iopub.status.idle":"2024-12-08T19:55:15.897388Z","shell.execute_reply.started":"2024-12-08T19:55:15.817907Z","shell.execute_reply":"2024-12-08T19:55:15.896528Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_desc.head(5)","metadata":{"_uuid":"1d415081-7682-4075-b43e-029fed9dfce9","_cell_guid":"2f8ae886-a921-4225-a054-a27d4905cd92","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.898452Z","iopub.execute_input":"2024-12-08T19:55:15.898712Z","iopub.status.idle":"2024-12-08T19:55:15.906857Z","shell.execute_reply.started":"2024-12-08T19:55:15.898687Z","shell.execute_reply":"2024-12-08T19:55:15.906013Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head(5)","metadata":{"_uuid":"cef110ca-27cf-4fc1-910d-23b5a547d0d3","_cell_guid":"ab502f68-03d8-4528-a3be-94f4f779b585","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.909044Z","iopub.execute_input":"2024-12-08T19:55:15.909291Z","iopub.status.idle":"2024-12-08T19:55:15.93342Z","shell.execute_reply.started":"2024-12-08T19:55:15.909267Z","shell.execute_reply":"2024-12-08T19:55:15.932626Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_desc.head(5)","metadata":{"_uuid":"99f0ac80-2e2e-4f03-8dce-52731c30859d","_cell_guid":"2dd01259-1fce-43b3-99b7-2abc79c1b504","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.934478Z","iopub.execute_input":"2024-12-08T19:55:15.934805Z","iopub.status.idle":"2024-12-08T19:55:15.944662Z","shell.execute_reply.started":"2024-12-08T19:55:15.934767Z","shell.execute_reply":"2024-12-08T19:55:15.943961Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"c415487a-ce65-43b4-8b73-d640b61e7539","_cell_guid":"a880ae41-973c-4bb0-992e-67c9ebab8882","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:15.945562Z","iopub.execute_input":"2024-12-08T19:55:15.945795Z","iopub.status.idle":"2024-12-08T19:55:18.780254Z","shell.execute_reply.started":"2024-12-08T19:55:15.945771Z","shell.execute_reply":"2024-12-08T19:55:18.779493Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_desc)","metadata":{"_uuid":"e751b8a7-4b31-4106-9f37-58c947f58d76","_cell_guid":"31a5f5f0-0e66-4661-bd58-a9f67e412f9e","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:18.781287Z","iopub.execute_input":"2024-12-08T19:55:18.781556Z","iopub.status.idle":"2024-12-08T19:55:18.786972Z","shell.execute_reply.started":"2024-12-08T19:55:18.781526Z","shell.execute_reply":"2024-12-08T19:55:18.786056Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_image_paths)","metadata":{"_uuid":"c7adf3eb-594d-45ef-85d4-e204f6a93b9a","_cell_guid":"56cb4867-c138-4e0c-9087-736af0f5c960","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:18.788032Z","iopub.execute_input":"2024-12-08T19:55:18.788312Z","iopub.status.idle":"2024-12-08T19:55:18.797617Z","shell.execute_reply.started":"2024-12-08T19:55:18.788275Z","shell.execute_reply":"2024-12-08T19:55:18.796943Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"83ba2be8-bc9e-4e92-bb4d-65f0fee7e2ef","_cell_guid":"f5466a68-9037-42ef-b24f-4be9cf407b14","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:18.798608Z","iopub.execute_input":"2024-12-08T19:55:18.79884Z","iopub.status.idle":"2024-12-08T19:55:19.865387Z","shell.execute_reply.started":"2024-12-08T19:55:18.798817Z","shell.execute_reply":"2024-12-08T19:55:19.86447Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"5243793e-da04-45ae-828d-ed801368b695","_cell_guid":"a2b605fe-5623-4294-bdda-66aef6eaf118","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:19.866363Z","iopub.execute_input":"2024-12-08T19:55:19.866616Z","iopub.status.idle":"2024-12-08T19:55:19.871844Z","shell.execute_reply.started":"2024-12-08T19:55:19.866591Z","shell.execute_reply":"2024-12-08T19:55:19.871001Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"51f2b3d1-d8c2-4a4a-8c02-788da3235618","_cell_guid":"c3d2ceef-ecf7-4fc3-9232-a2924d0a096a","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:19.872837Z","iopub.execute_input":"2024-12-08T19:55:19.873138Z","iopub.status.idle":"2024-12-08T19:55:19.920334Z","shell.execute_reply.started":"2024-12-08T19:55:19.873111Z","shell.execute_reply":"2024-12-08T19:55:19.919641Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"7be12c9f-3e64-4976-a0fd-4ac3a92126d4","_cell_guid":"5adb0531-abbd-480a-9583-21c4b7b2c0e9","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:19.921393Z","iopub.execute_input":"2024-12-08T19:55:19.92165Z","iopub.status.idle":"2024-12-08T19:55:19.940729Z","shell.execute_reply.started":"2024-12-08T19:55:19.921625Z","shell.execute_reply":"2024-12-08T19:55:19.939858Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"97d53670-909c-4ec2-b8c4-1837610a19a6","_cell_guid":"34517b54-a59c-400e-b6b6-14c8528e6a77","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:19.943921Z","iopub.execute_input":"2024-12-08T19:55:19.944204Z","iopub.status.idle":"2024-12-08T19:55:20.088316Z","shell.execute_reply.started":"2024-12-08T19:55:19.944178Z","shell.execute_reply":"2024-12-08T19:55:20.087459Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Normal/Mild\"].value_counts().sum()","metadata":{"_uuid":"efdc84ac-30c2-48db-a02c-8b046b021cba","_cell_guid":"a3bd1b45-525d-4074-adb5-9d80be929c5d","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.089434Z","iopub.execute_input":"2024-12-08T19:55:20.089787Z","iopub.status.idle":"2024-12-08T19:55:20.186643Z","shell.execute_reply.started":"2024-12-08T19:55:20.089748Z","shell.execute_reply":"2024-12-08T19:55:20.185859Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_merged_df[final_merged_df[\"severity\"] == \"Moderate\"].value_counts().sum()","metadata":{"_uuid":"358896a5-3e30-416a-8fc6-6f45fe957ba5","_cell_guid":"2291e3dc-e34a-4f3a-a9be-c0d3ba51b9e7","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.187604Z","iopub.execute_input":"2024-12-08T19:55:20.187857Z","iopub.status.idle":"2024-12-08T19:55:20.220515Z","shell.execute_reply.started":"2024-12-08T19:55:20.187832Z","shell.execute_reply":"2024-12-08T19:55:20.219719Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"b246318d-4db9-4e99-86a3-5bc821c1e868","_cell_guid":"d543d157-8bd4-4524-9314-298053fd7c56","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.221516Z","iopub.execute_input":"2024-12-08T19:55:20.221773Z","iopub.status.idle":"2024-12-08T19:55:20.277316Z","shell.execute_reply.started":"2024-12-08T19:55:20.221748Z","shell.execute_reply":"2024-12-08T19:55:20.276662Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"9119846e-4806-419a-8f58-85e3a97a3287","_cell_guid":"68d91fa9-3dfb-459b-9830-0c0827f66813","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.27823Z","iopub.execute_input":"2024-12-08T19:55:20.278468Z","iopub.status.idle":"2024-12-08T19:55:20.286055Z","shell.execute_reply.started":"2024-12-08T19:55:20.278444Z","shell.execute_reply":"2024-12-08T19:55:20.285229Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data = expanded_test_desc\ntrain_data = final_merged_df","metadata":{"_uuid":"be5ce772-449a-4c4e-92b0-823bd1eada25","_cell_guid":"84074846-8559-4761-b5b2-006a2932df07","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.28707Z","iopub.execute_input":"2024-12-08T19:55:20.28731Z","iopub.status.idle":"2024-12-08T19:55:20.295224Z","shell.execute_reply.started":"2024-12-08T19:55:20.287287Z","shell.execute_reply":"2024-12-08T19:55:20.294519Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"4669b18a-c820-475b-9749-99ad75a847a1","_cell_guid":"7fc1c47a-ad9b-4c97-91e2-082f020312b5","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:20.296195Z","iopub.execute_input":"2024-12-08T19:55:20.297029Z","iopub.status.idle":"2024-12-08T19:55:31.373485Z","shell.execute_reply.started":"2024-12-08T19:55:20.296992Z","shell.execute_reply":"2024-12-08T19:55:31.372564Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.374654Z","iopub.execute_input":"2024-12-08T19:55:31.374949Z","iopub.status.idle":"2024-12-08T19:55:31.387824Z","shell.execute_reply.started":"2024-12-08T19:55:31.374923Z","shell.execute_reply":"2024-12-08T19:55:31.386932Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data['series_description'].value_counts()","metadata":{"_uuid":"a57c73f6-825b-43af-96ac-3a353df717de","_cell_guid":"2d54c3f0-e460-415e-868a-a6443c1b6ef9","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.389091Z","iopub.execute_input":"2024-12-08T19:55:31.389434Z","iopub.status.idle":"2024-12-08T19:55:31.401908Z","shell.execute_reply.started":"2024-12-08T19:55:31.389398Z","shell.execute_reply":"2024-12-08T19:55:31.400828Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dicom(path):\n    dicom = pydicom.dcmread(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":{"_uuid":"3a46cd85-4e13-4c02-9733-05605860394a","_cell_guid":"25e65a1e-a70a-4a0f-b727-2eb4095eb0f1","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.403232Z","iopub.execute_input":"2024-12-08T19:55:31.403569Z","iopub.status.idle":"2024-12-08T19:55:31.412278Z","shell.execute_reply.started":"2024-12-08T19:55:31.403522Z","shell.execute_reply":"2024-12-08T19:55:31.411309Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"ad73bf3f-f4fc-462d-a9e8-408fa2c2af99","_cell_guid":"35086db2-a795-4854-ae0a-908316221ea1","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.413431Z","iopub.execute_input":"2024-12-08T19:55:31.413734Z","iopub.status.idle":"2024-12-08T19:55:31.786417Z","shell.execute_reply.started":"2024-12-08T19:55:31.4137Z","shell.execute_reply":"2024-12-08T19:55:31.785488Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data","metadata":{"_uuid":"e3c303b1-44d3-47ce-8de1-0e8a2c65fbf9","_cell_guid":"30589247-fcbb-494d-a78c-575452d6d4f8","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.787472Z","iopub.execute_input":"2024-12-08T19:55:31.787753Z","iopub.status.idle":"2024-12-08T19:55:31.802985Z","shell.execute_reply.started":"2024-12-08T19:55:31.787727Z","shell.execute_reply":"2024-12-08T19:55:31.802067Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data = train_data.dropna()","metadata":{"_uuid":"3dd21b32-8638-4b73-96dc-9adf8f3595f1","_cell_guid":"a9532a0a-1779-4339-b133-d7ae2e24c81b","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.804135Z","iopub.execute_input":"2024-12-08T19:55:31.804457Z","iopub.status.idle":"2024-12-08T19:55:31.834966Z","shell.execute_reply.started":"2024-12-08T19:55:31.804422Z","shell.execute_reply":"2024-12-08T19:55:31.833602Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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 numpy as np\nimport torch\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'].iloc[index]\n        image = load_dicom(image_path)  # Replace with your function to load DICOM images\n        label = self.dataframe['severity'].iloc[index]\n        \n        if self.transform:\n            image = self.transform(image)\n\n        return image, label\n\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    \"\"\"\n    Creates train and validation DataLoaders for a given series_description.\n    \"\"\"\n    # Filter DataFrame\n    filtered_df = df[df['series_description'] == series_description]\n    \n    # Check if data exists for the given series_description\n    if filtered_df.empty:\n        print(f\"Warning: No data found for series_description: {series_description}\")\n        return None, None, 0, 0\n\n    # Split into train and validation sets\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    # Create datasets and dataloaders\n    train_dataset = CustomDataset(train_df, transform=transform)\n    val_dataset = CustomDataset(val_df, transform=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\n# Define the transforms\ntransform = transforms.Compose([\n    transforms.Lambda(lambda x: (x * 255).astype(np.uint8)),  # Ensure uint8 for PIL\n    transforms.ToPILImage(),\n    transforms.Resize((224, 224)),\n    transforms.Grayscale(num_output_channels=3),  # Convert to 3-channel grayscale\n    transforms.ToTensor(),\n])\n\n# Series descriptions to process\nseries_descriptions = ['Sagittal T1', 'Axial T2', 'Sagittal T2/STIR']\n\n# Dictionaries to store loaders and dataset lengths\ndataloaders = {}\nlengths = {}\n\n# Create DataLoaders dynamically for each series_description\nfor description in series_descriptions:\n    trainloader, valloader, len_train, len_val = create_datasets_and_loaders(train_data, description, transform)\n    \n    if trainloader is not None and valloader is not None:\n        dataloaders[description] = (trainloader, valloader)\n        lengths[description] = (len_train, len_val)\n\n# Dictionary mapping labels to indices\nlabel_map = {'Mild': 0, 'Moderate': 1, 'Severe': 2}\n","metadata":{"_uuid":"7bdbd6bc-f7d4-4a47-a853-02d879ef6580","_cell_guid":"520f1c54-a2bf-4c06-a5c3-6bec52d6c225","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.836651Z","iopub.execute_input":"2024-12-08T19:55:31.836949Z","iopub.status.idle":"2024-12-08T19:55:31.886327Z","shell.execute_reply.started":"2024-12-08T19:55:31.836907Z","shell.execute_reply":"2024-12-08T19:55:31.883426Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"3b27baa3-93ee-4fee-81a7-39e3e74a7494","_cell_guid":"6052204f-7042-4945-95f5-fbf6fb098c91","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:31.88729Z","iopub.execute_input":"2024-12-08T19:55:31.887595Z","iopub.status.idle":"2024-12-08T19:55:34.046505Z","shell.execute_reply.started":"2024-12-08T19:55:31.887554Z","shell.execute_reply":"2024-12-08T19:55:34.045658Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"39d48b28-5eb0-489d-9a89-c728455eef9e","_cell_guid":"70bbd32d-7c59-4311-878e-964176c7a9cb","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:34.047771Z","iopub.execute_input":"2024-12-08T19:55:34.048497Z","iopub.status.idle":"2024-12-08T19:55:34.404783Z","shell.execute_reply.started":"2024-12-08T19:55:34.048456Z","shell.execute_reply":"2024-12-08T19:55:34.404037Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"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":{"_uuid":"2173ec73-0d9f-4a8b-87a2-d44c8075f598","_cell_guid":"e00805d2-5c24-4221-a8f0-30eb32f326c9","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:34.405983Z","iopub.execute_input":"2024-12-08T19:55:34.406567Z","iopub.status.idle":"2024-12-08T19:55:34.411945Z","shell.execute_reply.started":"2024-12-08T19:55:34.406528Z","shell.execute_reply":"2024-12-08T19:55:34.411047Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.optim as optim\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\n# Cihaz seçimi\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Özel ResNet50 modeli tanımlama\nclass CustomResNet50(nn.Module):\n    def __init__(self, num_classes=3, pretrained_weights=None):\n        super(CustomResNet50, self).__init__()\n        # ResNet50 modelini yükle\n        self.model = models.resnet50(weights=pretrained_weights)\n        # Son fully connected katmanını yeniden tanımla\n        num_ftrs = self.model.fc.in_features\n        self.model.fc = nn.Linear(num_ftrs, num_classes)\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# Modelleri oluştur ve cihaz üzerine taşı\nsagittal_t1_model = CustomResNet50(num_classes=3, pretrained_weights=models.ResNet50_Weights.DEFAULT).to(device)\naxial_t2_model = CustomResNet50(num_classes=3, pretrained_weights=models.ResNet50_Weights.DEFAULT).to(device)\nsagittal_t2stir_model = CustomResNet50(num_classes=3, pretrained_weights=models.ResNet50_Weights.DEFAULT).to(device)\n\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\ncriterion = nn.CrossEntropyLoss()\n\n# Optimizer ayarları\noptimizer_sagittal_t1 = optim.Adam(sagittal_t1_model.parameters(), lr=0.001)\noptimizer_axial_t2 = optim.Adam(axial_t2_model.parameters(), lr=0.001)\noptimizer_sagittal_t2stir = optim.Adam(sagittal_t2stir_model.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# 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}\")\n\n","metadata":{"_uuid":"f0e94411-3f50-4888-9b7a-8162a34b5338","_cell_guid":"6fc8f51f-64ab-4719-b4bd-6b0cf88958c8","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T19:55:34.413416Z","iopub.execute_input":"2024-12-08T19:55:34.413773Z","iopub.status.idle":"2024-12-08T19:55:36.170323Z","shell.execute_reply.started":"2024-12-08T19:55:34.413736Z","shell.execute_reply":"2024-12-08T19:55:36.169419Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_map = {'normal_mild': 0, 'moderate': 1, 'severe': 2}\n\n","metadata":{"_uuid":"bcb106c7-bed9-484b-9d59-2772630773c5","_cell_guid":"729b73a5-8c6a-4a3b-9fad-28bfe056813a","trusted":true,"collapsed":false,"jupyter":{"outputs_hidden":false}},"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-08T20:16:43.802247Z","iopub.execute_input":"2024-12-08T20:16:43.803116Z","iopub.status.idle":"2024-12-08T20:16:43.956549Z","shell.execute_reply.started":"2024-12-08T20:16:43.803066Z","shell.execute_reply":"2024-12-08T20:16:43.955668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.optim.lr_scheduler as lr_scheduler\nfrom copy import deepcopy\n\ndef train_model(model, trainloader, valloader, len_train, len_val, optimizer, num_epochs=10, patience=3, min_delta=0.001):\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  # Early stopping counter\n    prev_val_loss = float('inf')  # Previous validation loss to track changes\n    \n    for epoch in range(num_epochs):\n        model.train()\n        train_loss = 0\n        correct_train = 0\n        \n        # Training loop\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        # Validation loop\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).squeeze(0)\n                    _, predicted = torch.max(probabilities, 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        # Check for minimal change in validation loss (plateau-based early stopping)\n        if abs(prev_val_loss - val_loss) < min_delta:\n            counter += 1\n        else:\n            counter = 0\n        \n        prev_val_loss = val_loss  # Update previous validation loss\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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-08T20:16:48.729132Z","iopub.execute_input":"2024-12-08T20:16:48.729552Z","iopub.status.idle":"2024-12-08T20:16:48.74673Z","shell.execute_reply.started":"2024-12-08T20:16:48.729511Z","shell.execute_reply":"2024-12-08T20:16:48.745915Z"}},"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-08T20:16:51.896268Z","iopub.execute_input":"2024-12-08T20:16:51.896867Z","iopub.status.idle":"2024-12-08T22:33:27.951463Z","shell.execute_reply.started":"2024-12-08T20:16:51.896834Z","shell.execute_reply":"2024-12-08T22:33:27.950542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data['level'].unique()","metadata":{"_uuid":"741dd6fd-b3fe-4f03-8098-61506defda91","_cell_guid":"e68ce54a-11a6-402e-9e54-5a42e55ea898","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:33:58.555979Z","iopub.execute_input":"2024-12-08T22:33:58.556337Z","iopub.status.idle":"2024-12-08T22:33:58.566729Z","shell.execute_reply.started":"2024-12-08T22:33:58.556308Z","shell.execute_reply":"2024-12-08T22:33:58.565788Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"expanded_test_desc.head(5)","metadata":{"_uuid":"a92b2932-85c9-4fca-8ba9-24594772b297","_cell_guid":"4172babf-56ff-42a3-8b0d-c984ee5d1b11","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:01.60362Z","iopub.execute_input":"2024-12-08T22:34:01.604293Z","iopub.status.idle":"2024-12-08T22:34:01.613769Z","shell.execute_reply.started":"2024-12-08T22:34:01.604259Z","shell.execute_reply":"2024-12-08T22:34:01.612853Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"8b36a715-84d7-4937-be23-02c7d5afc729","_cell_guid":"d5505d39-350e-4540-bd93-d210ab4bf1f1","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:04.526284Z","iopub.execute_input":"2024-12-08T22:34:04.526627Z","iopub.status.idle":"2024-12-08T22:34:04.534106Z","shell.execute_reply.started":"2024-12-08T22:34:04.526597Z","shell.execute_reply":"2024-12-08T22:34:04.533254Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"expanded_test_desc.head(2)","metadata":{"_uuid":"8ca975ef-3b99-449b-bd61-40b2bf07b03c","_cell_guid":"78573fd8-f419-460b-9580-bf683850d68f","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:07.236148Z","iopub.execute_input":"2024-12-08T22:34:07.236497Z","iopub.status.idle":"2024-12-08T22:34:07.245732Z","shell.execute_reply.started":"2024-12-08T22:34:07.236466Z","shell.execute_reply":"2024-12-08T22:34:07.24479Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"62598840-7c05-4874-b9ae-791d2d2c9c87","_cell_guid":"0eb1ebdc-9b11-4cc1-9c83-7f5db522b2de","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:11.249659Z","iopub.execute_input":"2024-12-08T22:34:11.250025Z","iopub.status.idle":"2024-12-08T22:34:11.257143Z","shell.execute_reply.started":"2024-12-08T22:34:11.249994Z","shell.execute_reply":"2024-12-08T22:34:11.256203Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for image in testloader:\n    print(image.shape)\n    break","metadata":{"_uuid":"b43ba749-b01f-4d5f-bd88-80969bee8c7f","_cell_guid":"96290232-5a34-43e7-a612-3a2b3fca1cc8","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:17.008518Z","iopub.execute_input":"2024-12-08T22:34:17.009334Z","iopub.status.idle":"2024-12-08T22:34:17.039884Z","shell.execute_reply.started":"2024-12-08T22:34:17.009301Z","shell.execute_reply":"2024-12-08T22:34:17.039079Z"},"jupyter":{"outputs_hidden":false}},"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:34:20.374536Z","iopub.execute_input":"2024-12-08T22:34:20.375379Z","iopub.status.idle":"2024-12-08T22:34:20.382183Z","shell.execute_reply.started":"2024-12-08T22:34:20.375343Z","shell.execute_reply":"2024-12-08T22:34:20.38139Z"}},"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:34:25.146356Z","iopub.execute_input":"2024-12-08T22:34:25.147085Z","iopub.status.idle":"2024-12-08T22:34:30.24176Z","shell.execute_reply.started":"2024-12-08T22:34:25.14705Z","shell.execute_reply":"2024-12-08T22:34:30.240922Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_predictions[0]","metadata":{"_uuid":"527b8461-11c7-4992-a6d7-15925b1ef1cd","_cell_guid":"604248cb-8e23-456c-925e-f9e7eda60b43","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:33.06275Z","iopub.execute_input":"2024-12-08T22:34:33.063536Z","iopub.status.idle":"2024-12-08T22:34:33.237426Z","shell.execute_reply.started":"2024-12-08T22:34:33.063492Z","shell.execute_reply":"2024-12-08T22:34:33.236541Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"dd2e1373-6954-4d15-aeaf-a83f538159bd","_cell_guid":"393c195b-8446-4421-bac5-cfda177cb8b1","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:37.282712Z","iopub.execute_input":"2024-12-08T22:34:37.283338Z","iopub.status.idle":"2024-12-08T22:34:37.288781Z","shell.execute_reply.started":"2024-12-08T22:34:37.283303Z","shell.execute_reply":"2024-12-08T22:34:37.287865Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = expanded_test_desc[[\"row_id\",\"normal_mild\",\"moderate\",\"severe\"]]","metadata":{"_uuid":"8928df85-56fb-42d5-87dc-98dad3bf089b","_cell_guid":"de33888f-a668-428c-8c3f-4f3730277c2c","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:40.085714Z","iopub.execute_input":"2024-12-08T22:34:40.086063Z","iopub.status.idle":"2024-12-08T22:34:40.091368Z","shell.execute_reply.started":"2024-12-08T22:34:40.086031Z","shell.execute_reply":"2024-12-08T22:34:40.090463Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head(10)","metadata":{"_uuid":"73b3b554-b887-4c74-964d-4cf62e7f07f9","_cell_guid":"a2b5f217-0b7e-4c80-af5f-d643d83347b7","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:34:42.344369Z","iopub.execute_input":"2024-12-08T22:34:42.344704Z","iopub.status.idle":"2024-12-08T22:34:42.35516Z","shell.execute_reply.started":"2024-12-08T22:34:42.344675Z","shell.execute_reply":"2024-12-08T22:34:42.354304Z"},"jupyter":{"outputs_hidden":false}},"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":{"_uuid":"a3e89712-116c-4ce0-b3b0-c240caea9557","_cell_guid":"e9e8517f-14ae-4a96-b2bf-6125880c3b13","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:35:04.828814Z","iopub.execute_input":"2024-12-08T22:35:04.829184Z","iopub.status.idle":"2024-12-08T22:35:04.848931Z","shell.execute_reply.started":"2024-12-08T22:35:04.829154Z","shell.execute_reply":"2024-12-08T22:35:04.847954Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(grouped_submission)","metadata":{"_uuid":"909986e0-1c9c-4009-a111-616a85a7fc09","_cell_guid":"072bf091-9212-4062-b453-ffa094c81bcd","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:35:09.980082Z","iopub.execute_input":"2024-12-08T22:35:09.980986Z","iopub.status.idle":"2024-12-08T22:35:09.988137Z","shell.execute_reply.started":"2024-12-08T22:35:09.980938Z","shell.execute_reply":"2024-12-08T22:35:09.987265Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub[['normal_mild', 'moderate', 'severe']] = grouped_submission[['normal_mild', 'moderate', 'severe']]","metadata":{"_uuid":"0719c038-737f-40f9-92f2-f64115df9e77","_cell_guid":"b4d366e5-6366-433c-8b24-17774840d0aa","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:35:15.129201Z","iopub.execute_input":"2024-12-08T22:35:15.130215Z","iopub.status.idle":"2024-12-08T22:35:15.1354Z","shell.execute_reply.started":"2024-12-08T22:35:15.130183Z","shell.execute_reply":"2024-12-08T22:35:15.134532Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# Save the DataFrame to \"submission.csv\" in the desired directory\nsub.to_csv(\"/kaggle/working/submission.csv\", index=False)","metadata":{"_uuid":"db985479-c836-435c-8b96-9ebabe4f1bce","_cell_guid":"b5f2e7eb-53b1-4cde-8ef2-5be54e6f0d77","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:35:19.488111Z","iopub.execute_input":"2024-12-08T22:35:19.489048Z","iopub.status.idle":"2024-12-08T22:35:19.495625Z","shell.execute_reply.started":"2024-12-08T22:35:19.489014Z","shell.execute_reply":"2024-12-08T22:35:19.494919Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub.head(5)","metadata":{"_uuid":"884a814f-3083-4d79-b925-7296c929d252","_cell_guid":"3acb3eee-bffb-4d8c-9c1f-d1740485bed8","trusted":true,"collapsed":false,"execution":{"iopub.status.busy":"2024-12-08T22:35:21.958159Z","iopub.execute_input":"2024-12-08T22:35:21.958961Z","iopub.status.idle":"2024-12-08T22:35:21.967987Z","shell.execute_reply.started":"2024-12-08T22:35:21.958927Z","shell.execute_reply":"2024-12-08T22:35:21.967095Z"},"jupyter":{"outputs_hidden":false}},"outputs":[],"execution_count":null}]}