{"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":"INPUT_MODEL_PATH = \"/kaggle/input/kacper-model-1/model.h5\"\nMODEL_PATH = \"/kaggle/working/model.h5\"","metadata":{"execution":{"iopub.status.busy":"2023-10-06T19:32:28.7664Z","iopub.execute_input":"2023-10-06T19:32:28.766792Z","iopub.status.idle":"2023-10-06T19:32:28.771894Z","shell.execute_reply.started":"2023-10-06T19:32:28.766762Z","shell.execute_reply":"2023-10-06T19:32:28.770849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pydicom\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport cv2\nimport os\nimport pandas as pd\nimport numpy as np\n\n\nimport tensorflow as tf\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import layers, models\n\n\n\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\nimport keras_core as keras\nimport keras_cv","metadata":{"execution":{"iopub.status.busy":"2023-10-07T11:17:19.470342Z","iopub.execute_input":"2023-10-07T11:17:19.470662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"! cp {INPUT_MODEL_PATH} ./\n\nmodel = keras.models.load_model(MODEL_PATH)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-10-06T19:32:29.404893Z","iopub.execute_input":"2023-10-06T19:32:29.405273Z","iopub.status.idle":"2023-10-06T19:32:31.950248Z","shell.execute_reply.started":"2023-10-06T19:32:29.405245Z","shell.execute_reply":"2023-10-06T19:32:31.949251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_path = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/test_images/\"\n\nimage_paths = []\npatient_ids_from_paths = []\n\nfor dirpath, dirnames, filenames in os.walk(base_path):\n    for filename in filenames:\n        full_path = os.path.join(dirpath, filename)\n        \n        if \"3124/5842/514.dcm\" in full_path:\n            continue\n        \n        if not os.path.exists(full_path):\n            continue\n        \n        if filename.endswith('.dcm'):\n            image_paths.append(full_path)\n            parent_dir = os.path.dirname(dirpath)\n            patient_id = os.path.basename(parent_dir) \n            patient_ids_from_paths.append(int(patient_id))\n\ndef load_and_process_image(path):\n    ds = pydicom.dcmread(path)\n    img = ds.pixel_array\n    img = tf.convert_to_tensor(img, dtype=tf.float32)\n    img = tf.expand_dims(img, axis=-1)\n    img = tf.image.grayscale_to_rgb(img)\n    img = tf.image.resize(img, [512, 512])\n    img = img / 255.0\n    return img\n\ndef load_and_process_images_batch(image_paths_batch):\n    return [load_and_process_image(path) for path in image_paths_batch]\n\ncategories = {\n    'bowel': ['healthy', 'injury'],\n    'extravasation': ['healthy', 'injury'],\n    'kidney': ['healthy', 'low', 'high'],\n    'liver': ['healthy', 'low', 'high'],\n    'spleen': ['healthy', 'low', 'high']\n}\n\n\nsample_submission = pd.read_csv('/kaggle/input/rsna-2023-abdominal-trauma-detection/sample_submission.csv')\nsample_submission.set_index('patient_id', inplace=True)\n\nall_results = []\n\nBATCH_SIZE = 10\nfor i in range(0, len(image_paths), BATCH_SIZE):\n    image_paths_batch = image_paths[i:i+BATCH_SIZE]\n    test_images_batch = load_and_process_images_batch(image_paths_batch)\n    test_images_ds_batch = tf.data.Dataset.from_tensor_slices(test_images_batch).batch(len(image_paths_batch))\n    \n    predictions_batch = model.predict(test_images_ds_batch)\n    \n    data = {}\n    for a, (category, subcats) in enumerate(categories.items()):\n        preds = predictions_batch[a]\n        for j, subcat in enumerate(subcats):\n            col_name = f\"{category}_{subcat}\"\n            data[col_name] = preds[:, j]\n    \n    df_batch = pd.DataFrame(data)\n    patient_ids_batch = patient_ids_from_paths[i:i+BATCH_SIZE]\n    df_batch['patient_id'] = patient_ids_batch\n    all_results.append(df_batch)\n\nall_results_df = pd.concat(all_results)\naverage_results = all_results_df.groupby('patient_id').mean()\n\nfor idx in average_results.index:\n    for col in average_results.columns:\n        if col in sample_submission.columns:\n            sample_submission.at[idx, col] = average_results.at[idx, col]\n\nsample_submission.reset_index(inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-06T19:32:31.952256Z","iopub.execute_input":"2023-10-06T19:32:31.953251Z","iopub.status.idle":"2023-10-06T19:32:32.021345Z","shell.execute_reply.started":"2023-10-06T19:32:31.953218Z","shell.execute_reply":"2023-10-06T19:32:32.019607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-06T19:32:38.908282Z","iopub.execute_input":"2023-10-06T19:32:38.908898Z","iopub.status.idle":"2023-10-06T19:32:38.915787Z","shell.execute_reply.started":"2023-10-06T19:32:38.908866Z","shell.execute_reply":"2023-10-06T19:32:38.914665Z"},"trusted":true},"execution_count":null,"outputs":[]}]}