{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"train_path = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/*.dcm'","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:54:56.941853Z","iopub.execute_input":"2023-08-07T17:54:56.942296Z","iopub.status.idle":"2023-08-07T17:54:56.955094Z","shell.execute_reply.started":"2023-08-07T17:54:56.942266Z","shell.execute_reply":"2023-08-07T17:54:56.954077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import necessary libraries\nimport glob                   # For file path matching\nimport numpy as np            # For numerical operations\nimport pandas as pd           # For data manipulation\nimport matplotlib.pyplot as plt  # For data visualization\nimport os                     # For interacting with the operating system\nimport pydicom as dicom       # For working with DICOM files (medical imaging)\nimport random                 # For random number generation\nrandom.seed(42)              # Set a random seed for reproducibility\n\nimport torch                  # For PyTorch-based deep learning\nimport torch.nn as nn         # For defining neural network modules\nimport torch.optim as optim   # For defining optimization algorithms\n\nimport tensorflow as tf       # For TensorFlow-based deep learning\nfrom tensorflow.keras import layers, models  # For defining Keras models and layers","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:54:56.959007Z","iopub.execute_input":"2023-08-07T17:54:56.959315Z","iopub.status.idle":"2023-08-07T17:55:10.88173Z","shell.execute_reply.started":"2023-08-07T17:54:56.959286Z","shell.execute_reply":"2023-08-07T17:55:10.880611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_train_examples = len(train_path)\nprint(num_train_examples)","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:14.856635Z","iopub.execute_input":"2023-08-07T17:55:14.857817Z","iopub.status.idle":"2023-08-07T17:55:14.863218Z","shell.execute_reply.started":"2023-08-07T17:55:14.857781Z","shell.execute_reply":"2023-08-07T17:55:14.862225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pixel_arries = []\npixel_number = []\n\nfor _ in range(min(6, num_train_examples)):\n    randomly_selected_image = random.choice(os.listdir('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057'))\n    pixel_arries.append(dicom.dcmread('/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10004/21057/' + randomly_selected_image).pixel_array)\n    pixel_number.append(randomly_selected_image)","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:18.496238Z","iopub.execute_input":"2023-08-07T17:55:18.496644Z","iopub.status.idle":"2023-08-07T17:55:18.715885Z","shell.execute_reply.started":"2023-08-07T17:55:18.496609Z","shell.execute_reply":"2023-08-07T17:55:18.714825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# randomly show some figures for checking\nplt.figure(figsize=(10, 8))\nfor x in range(min(6, num_train_examples)):\n    plt.subplot(2, 3, x + 1)\n    plt.imshow(pixel_arries[x], cmap='bone')\n    plt.title(pixel_number[x])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:21.346692Z","iopub.execute_input":"2023-08-07T17:55:21.347052Z","iopub.status.idle":"2023-08-07T17:55:22.622238Z","shell.execute_reply.started":"2023-08-07T17:55:21.347024Z","shell.execute_reply":"2023-08-07T17:55:22.621354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv('/kaggle/input/rsna-2023-abdominal-trauma-detection/train.csv')","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:26.146105Z","iopub.execute_input":"2023-08-07T17:55:26.147336Z","iopub.status.idle":"2023-08-07T17:55:26.167558Z","shell.execute_reply.started":"2023-08-07T17:55:26.14726Z","shell.execute_reply":"2023-08-07T17:55:26.166345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head().style.set_properties(**{'background-color': 'black',\n                                                'color': 'lawngreen',\n                                                'border': '1.5px  white'})","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:28.892004Z","iopub.execute_input":"2023-08-07T17:55:28.892383Z","iopub.status.idle":"2023-08-07T17:55:28.96027Z","shell.execute_reply.started":"2023-08-07T17:55:28.892355Z","shell.execute_reply":"2023-08-07T17:55:28.959144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert patient_id column from DataFrame to a numpy array and cast it to string data type\nid = df_train.patient_id.to_numpy().astype(str)\n\n# Initialize empty lists for storing image data (X) and corresponding labels (y)\nX, y = [], []\n\n# Loop over the first 3 patient IDs\nfor x, p_id in enumerate(id[:3]):\n    # Define the directory path for the current patient's images\n    dir = '/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/' + p_id + '/'\n    \n    # Extract the features (labels) for the current patient using their index\n    features = df_train.iloc[x].to_numpy()[1:]\n    \n    # Loop through each file in the patient's directory\n    for file in glob.glob(dir + '*'):\n        # Loop through each image file in the current directory\n        for image_path in glob.glob(file + '/*'):\n            # Read the DICOM image and extract the pixel array\n            X.append(dicom.dcmread(image_path).pixel_array)\n            \n            # Append the features (labels) for this image to the y list\n            y.append(features)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:55:30.777913Z","iopub.execute_input":"2023-08-07T17:55:30.778504Z","iopub.status.idle":"2023-08-07T17:56:13.715408Z","shell.execute_reply.started":"2023-08-07T17:55:30.778473Z","shell.execute_reply":"2023-08-07T17:56:13.71438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(X), len(y)","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:56:13.71743Z","iopub.execute_input":"2023-08-07T17:56:13.717791Z","iopub.status.idle":"2023-08-07T17:56:13.7269Z","shell.execute_reply.started":"2023-08-07T17:56:13.717759Z","shell.execute_reply":"2023-08-07T17:56:13.725847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = np.array(X)\ny = np.array(y)\n\nX.shape, y.shape","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:56:17.38122Z","iopub.execute_input":"2023-08-07T17:56:17.38257Z","iopub.status.idle":"2023-08-07T17:56:18.137699Z","shell.execute_reply.started":"2023-08-07T17:56:17.382528Z","shell.execute_reply":"2023-08-07T17:56:18.136574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10, 8))\nplt.imshow(X[1], cmap='bone')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:56:24.342321Z","iopub.execute_input":"2023-08-07T17:56:24.342723Z","iopub.status.idle":"2023-08-07T17:56:24.788958Z","shell.execute_reply.started":"2023-08-07T17:56:24.342693Z","shell.execute_reply":"2023-08-07T17:56:24.787956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This notebook is inspired by import tensorflow as tf\n\n# Define the input layer\ninputs = tf.keras.Input(shape=(X.shape[1], X.shape[2], 1))\n\n# First set of convolutional layers\nx = tf.keras.layers.Conv2D(2, (3, 3), activation='relu')(inputs)\nx = tf.keras.layers.Conv2D(2, (3, 3), activation='relu')(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPool2D(2)(x)\n\n# Second set of convolutional layers\nx = tf.keras.layers.Conv2D(4, (3, 3), activation='relu')(x)\nx = tf.keras.layers.Conv2D(4, (3, 3), activation='relu')(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPool2D(2)(x)\n\n# Third set of convolutional layers\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPool2D(2)(x)\n\n# Fourth set of convolutional layers\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPool2D(2)(x)\n\n# Fifth set of convolutional layers\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.Conv2D(8, (3, 3), activation='relu')(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.MaxPool2D(2)(x)\n\n# Flatten the output\nx = tf.keras.layers.Flatten()(x)\n\n# Fully connected layer\nx = tf.keras.layers.Dense(64, activation='relu')(x)\n\n# Output layer\noutputs = tf.keras.layers.Dense(y.shape[1], activation='sigmoid')(x)\n\n# Create the model\nmodel = tf.keras.Model(inputs=inputs, outputs=outputs)\n\n# Compile the model\nopt = tf.keras.optimizers.Adam(learning_rate=0.0008, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False)\nmodel.compile(optimizer=opt, loss='mse', metrics=['mae'])\n\n# Print model summary\nmodel.summary()\n\n# Train the model\nhistory = model.fit(X, y, epochs=10, batch_size=512, validation_split=0.3, verbose=1, shuffle=True)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-07T17:59:36.480508Z","iopub.execute_input":"2023-08-07T17:59:36.480907Z","iopub.status.idle":"2023-08-07T18:01:02.588892Z","shell.execute_reply.started":"2023-08-07T17:59:36.480876Z","shell.execute_reply":"2023-08-07T18:01:02.58762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}