{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":52254,"databundleVersionId":6863140,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\ndirname = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-15T04:32:09.612513Z","iopub.execute_input":"2023-12-15T04:32:09.612756Z","iopub.status.idle":"2023-12-15T04:32:09.962525Z","shell.execute_reply.started":"2023-12-15T04:32:09.612732Z","shell.execute_reply":"2023-12-15T04:32:09.961721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filename = '/kaggle/input/rsna-2023-abdominal-trauma-detection/image_level_labels.csv'\ndf = pd.read_csv(filename)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:32:12.222145Z","iopub.execute_input":"2023-12-15T04:32:12.22264Z","iopub.status.idle":"2023-12-15T04:32:12.281103Z","shell.execute_reply.started":"2023-12-15T04:32:12.22261Z","shell.execute_reply":"2023-12-15T04:32:12.279986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_ext = df.loc[df['injury_name'] == 'Active_Extravasation']\ndf_ext","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:32:49.994589Z","iopub.execute_input":"2023-12-15T04:32:49.994923Z","iopub.status.idle":"2023-12-15T04:32:50.010098Z","shell.execute_reply.started":"2023-12-15T04:32:49.994895Z","shell.execute_reply":"2023-12-15T04:32:50.009231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = {\n    'patient_id': [],\n    'series_id': [],\n    'instance_number': [],\n}\n\ndf_all = pd.DataFrame(data)\ndf_all.head()","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:32:50.965477Z","iopub.execute_input":"2023-12-15T04:32:50.965798Z","iopub.status.idle":"2023-12-15T04:32:50.97536Z","shell.execute_reply.started":"2023-12-15T04:32:50.965773Z","shell.execute_reply":"2023-12-15T04:32:50.974409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"for dir in os.listdir(dirname):\n    for series in os.listdir(dirname+'/'+dir):\n        for img in os.listdir(dirname+'/'+dir+'/'+series):\n            new_row = {'patient_id': int(dir) ,'series_id': int(series),'instance_number': int(img.split('.')[0])}\n            df_all.loc[len(df_all)] = new_row\n    if len(df_all) > 100:\n        break\n","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:32:54.692787Z","iopub.execute_input":"2023-12-15T04:32:54.693541Z","iopub.status.idle":"2023-12-15T04:32:55.594502Z","shell.execute_reply.started":"2023-12-15T04:32:54.693508Z","shell.execute_reply":"2023-12-15T04:32:55.593499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all['patient_id'].dtype","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:03.183735Z","iopub.execute_input":"2023-12-15T04:33:03.184095Z","iopub.status.idle":"2023-12-15T04:33:03.190721Z","shell.execute_reply.started":"2023-12-15T04:33:03.184067Z","shell.execute_reply":"2023-12-15T04:33:03.189628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_all.sort_values(['patient_id','series_id','instance_number'],inplace=True)\ndf_all","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:06.069902Z","iopub.execute_input":"2023-12-15T04:33:06.070245Z","iopub.status.idle":"2023-12-15T04:33:06.096326Z","shell.execute_reply.started":"2023-12-15T04:33:06.070218Z","shell.execute_reply":"2023-12-15T04:33:06.095266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_df = pd.merge(df_all, df_ext[['patient_id','series_id','instance_number','injury_name']], on=['patient_id','series_id','instance_number'], how='outer')","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:07.250292Z","iopub.execute_input":"2023-12-15T04:33:07.251143Z","iopub.status.idle":"2023-12-15T04:33:07.274881Z","shell.execute_reply.started":"2023-12-15T04:33:07.251109Z","shell.execute_reply":"2023-12-15T04:33:07.274151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_df = merged_df.fillna(\"Healthy\")\nmerged_df","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:09.204078Z","iopub.execute_input":"2023-12-15T04:33:09.204765Z","iopub.status.idle":"2023-12-15T04:33:09.218542Z","shell.execute_reply.started":"2023-12-15T04:33:09.204733Z","shell.execute_reply":"2023-12-15T04:33:09.217559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_df = merged_df.sample(frac=1).reset_index(drop=True)\nmerged_df","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:10.921161Z","iopub.execute_input":"2023-12-15T04:33:10.921559Z","iopub.status.idle":"2023-12-15T04:33:10.939357Z","shell.execute_reply.started":"2023-12-15T04:33:10.92152Z","shell.execute_reply":"2023-12-15T04:33:10.938502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nfor index, row in merged_df.iterrows():\n    file_to_copy = dirname + '/' + str(row['patient_id']) + '/' + str(row['series_id']) + '/' + str(row['instance_number']) + '.dcm'\n    custom_filename = str(row['patient_id']) + str(row['series_id'])  + str(row['instance_number']) + '.dcm'\n    destination_directory = '/kaggle/working/'\n    destination_path = os.path.join(destination_directory, custom_filename)\n    shutil.copy(file_to_copy, destination_path)","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:33:49.221634Z","iopub.execute_input":"2023-12-15T04:33:49.221988Z","iopub.status.idle":"2023-12-15T04:35:40.65729Z","shell.execute_reply.started":"2023-12-15T04:33:49.221958Z","shell.execute_reply":"2023-12-15T04:35:40.656443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nfrom PIL import Image\nimport pydicom\n\nyour_dataset_path = '/kaggle/working/'\nyour_dicom_directory = '/kaggle/working/'\n\nyour_labels = np.array(merged_df['injury_name'])\ndicom_files = [f for f in os.listdir(your_dataset_path) if f.endswith(('.dcm'))]\n\nfirst_dicom_path = os.path.join(your_dicom_directory, dicom_files[0])\nfirst_dicom = pydicom.dcmread(first_dicom_path)\nimage_size = (int(first_dicom.Rows), int(first_dicom.Columns))\nprint(image_size,first_dicom)\nimages = []\nlabels = np.array(merged_df['injury_name'])\n\nfor dicom_file in dicom_files:\n    dicom_path = os.path.join(your_dicom_directory, dicom_file)\n    dicom_data = pydicom.dcmread(dicom_path)\n    pixel_array = dicom_data.pixel_array\n    image = Image.fromarray(pixel_array).resize(image_size)\n    image_array = np.array(image)\n    images.append(image_array)\n\nimages = np.array(images)\n\n# Split your dataset into training and testing sets\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(images, labels, test_size=0.2, random_state=42)\n\n# Display the shapes of the resulting sets\nprint(\"x_train shape:\", x_train.shape)\nprint(\"y_train shape:\", y_train.shape)\nprint(\"x_test shape:\", x_test.shape)\nprint(\"y_test shape:\", y_test.shape)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:35:55.835167Z","iopub.execute_input":"2023-12-15T04:35:55.835569Z","iopub.status.idle":"2023-12-15T04:37:52.911382Z","shell.execute_reply.started":"2023-12-15T04:35:55.835537Z","shell.execute_reply":"2023-12-15T04:37:52.910261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.reshape(5322, 673, 512,1)\nx_test.reshape(1331, 673, 512,1)","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:39:37.234096Z","iopub.execute_input":"2023-12-15T04:39:37.234462Z","iopub.status.idle":"2023-12-15T04:39:37.246181Z","shell.execute_reply.started":"2023-12-15T04:39:37.234433Z","shell.execute_reply":"2023-12-15T04:39:37.245249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.astype('float32') / 255.0 \nx_test = x_test.astype('float32') / 255.0","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:39:41.626852Z","iopub.execute_input":"2023-12-15T04:39:41.627846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\ndevice_name = tf.test.gpu_device_name()\nif len(device_name) > 0:\n    print(\"Found GPU at: {}\".format(device_name))\nelse:\n    device_name = \"/device:CPU:0\"\n    print(\"No GPU, using {}.\".format(device_name))","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:39:56.001101Z","iopub.execute_input":"2023-12-15T04:39:56.001443Z","iopub.status.idle":"2023-12-15T04:40:21.063482Z","shell.execute_reply.started":"2023-12-15T04:39:56.001414Z","shell.execute_reply":"2023-12-15T04:40:21.062483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers\n\ndef CreateCNN2():\n    model = tf.keras.Sequential([\n    layers.Conv2D(256, (3, 3), padding='same', input_shape=(512, 512, 1)),\n    layers.BatchNormalization(),\n    layers.LeakyReLU(alpha=0.01),\n\n    layers.Conv2D(32, (3, 3), padding='same'),\n    layers.BatchNormalization(),\n    layers.LeakyReLU(alpha=0.01),\n\n    layers.MaxPooling2D(pool_size=(2, 2)),  # Add max pooling layer\n\n    layers.Conv2D(64, (3, 3), padding='same'),\n    layers.BatchNormalization(),\n    layers.LeakyReLU(alpha=0.01),\n\n    layers.Conv2D(64, (3, 3), padding='same'),\n    layers.BatchNormalization(),\n    layers.LeakyReLU(alpha=0.01),\n\n    layers.MaxPooling2D(pool_size=(2, 2)),  # Add max pooling layer\n\n    layers.GlobalAveragePooling2D(),\n    layers.Dropout(0.5),\n\n    layers.Dense(256, activation='relu'),  # Add dense layer\n    layers.Dropout(0.5),  # Add dropout layer\n    layers.Dense(128, activation='relu'),  # Add dense layer\n    layers.Dropout(0.5),  # Add dropout layer\n    layers.Dense(10, activation='softmax')\n  ])\n\n    with tf.device(device_name):\n        model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n  \n    return model","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:41:03.537586Z","iopub.execute_input":"2023-12-15T04:41:03.539317Z","iopub.status.idle":"2023-12-15T04:41:03.748841Z","shell.execute_reply.started":"2023-12-15T04:41:03.539268Z","shell.execute_reply":"2023-12-15T04:41:03.747782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = CreateCNN2()\n","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:41:06.22436Z","iopub.execute_input":"2023-12-15T04:41:06.225488Z","iopub.status.idle":"2023-12-15T04:41:06.895977Z","shell.execute_reply.started":"2023-12-15T04:41:06.225438Z","shell.execute_reply":"2023-12-15T04:41:06.895141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(x_train \n          , y_train \n          , batch_size = 32 \n          , epochs = 4 \n          , shuffle = True \n          )","metadata":{"execution":{"iopub.status.busy":"2023-12-15T04:29:43.992362Z","iopub.execute_input":"2023-12-15T04:29:43.992741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\nfolder_path = '/kaggle/working/'\n\n# Get all files in the folder\nfiles = os.listdir(folder_path)\n\n# Iterate over each file and delete\nfor file in files:\n    file_path = os.path.join(folder_path, file)\n    try:\n        if os.path.isfile(file_path):\n            os.unlink(file_path)\n    except Exception as e:\n        print(f\"Error deleting {file_path}: {e}\")\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}