{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":113002,"databundleVersionId":13471427,"sourceType":"competition"},{"sourceId":267177235,"sourceType":"kernelVersion"}],"dockerImageVersionId":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport os\nimport timm\n\n\n\n\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T03:40:59.781086Z","iopub.execute_input":"2025-10-12T03:40:59.781375Z","iopub.status.idle":"2025-10-12T03:41:11.025148Z","shell.execute_reply.started":"2025-10-12T03:40:59.781332Z","shell.execute_reply":"2025-10-12T03:41:11.024533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 1. Configuration ---\n# IMPORTANT: Update this path to saved model file\nMODEL_PATH = '/kaggle/input/grand-x-ray-slam-division-b/best_model.pth' \n\n# Paths for the competition's test data\nTEST_DIR = '/kaggle/input/grand-xray-slam-division-b/test2'\nSAMPLE_SUBMISSION_PATH = '/kaggle/input/grand-xray-slam-division-b/sample_submission_2.csv'\n\n# Model settings (\nMODEL_NAME = 'efficientnet_b0'\nIMAGE_SIZE = 256\nBATCH_SIZE = 64 # Use a larger batch size for faster inference\nLABELS = [\n    'Atelectasis', 'Cardiomegaly', 'Consolidation', 'Edema',\n    'Enlarged Cardiomediastinum', 'Fracture', 'Lung Lesion',\n    'Lung Opacity', 'Pleural Effusion', 'Pleural Other',\n    'Pneumonia', 'Pneumothorax', 'Support Devices', 'No Finding'\n]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T03:41:11.026446Z","iopub.execute_input":"2025-10-12T03:41:11.026704Z","iopub.status.idle":"2025-10-12T03:41:11.030926Z","shell.execute_reply.started":"2025-10-12T03:41:11.026681Z","shell.execute_reply":"2025-10-12T03:41:11.0304Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 2. Load the Trained Model ---\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n# Re-create the model architecture\nmodel = timm.create_model(MODEL_NAME, pretrained=False, num_classes=len(LABELS))\n\n# Load your trained weights, mapping them to the correct device\nmodel.load_state_dict(torch.load(MODEL_PATH, map_location=device))\nmodel.to(device)\nmodel.eval() # Set model to evaluation mode (very important!)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T03:41:11.031706Z","iopub.execute_input":"2025-10-12T03:41:11.03194Z","iopub.status.idle":"2025-10-12T03:41:11.74527Z","shell.execute_reply.started":"2025-10-12T03:41:11.031919Z","shell.execute_reply":"2025-10-12T03:41:11.744539Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 3. Create Test Dataset and DataLoader ---\n# This is a simplified dataset for test images, as they have no labels\nclass TestXRayDataset(Dataset):\n    def __init__(self, image_paths, transform=None):\n        self.image_paths = image_paths\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.image_paths)\n\n    def __getitem__(self, idx):\n        image_path = self.image_paths[idx]\n        image = Image.open(image_path).convert(\"RGB\")\n        if self.transform:\n            image = self.transform(image)\n        return image, os.path.basename(image_path)\n\n# Use the same normalization as your validation set\ntest_transform = transforms.Compose([\n    transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\n# Get list of test image paths\ntest_image_paths = [os.path.join(TEST_DIR, f) for f in os.listdir(TEST_DIR)]\n\ntest_dataset = TestXRayDataset(test_image_paths, transform=test_transform)\ntest_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T03:41:11.746456Z","iopub.execute_input":"2025-10-12T03:41:11.746649Z","iopub.status.idle":"2025-10-12T03:41:12.535708Z","shell.execute_reply.started":"2025-10-12T03:41:11.746634Z","shell.execute_reply":"2025-10-12T03:41:12.534918Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 4. Generate Predictions ---\nall_preds = []\nall_img_names = []\n\nprint(\"Starting inference...\")\nwith torch.no_grad(): # Disable gradient calculation for speed\n    for images, img_names in test_loader:\n        images = images.to(device)\n        outputs = model(images)\n        # Use sigmoid to convert model outputs to probabilities (0 to 1)\n        preds = torch.sigmoid(outputs)\n        \n        all_preds.append(preds.cpu().numpy())\n        all_img_names.extend(img_names)\n\nall_preds = np.vstack(all_preds)\nprint(\"Inference complete.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T03:41:12.536542Z","iopub.execute_input":"2025-10-12T03:41:12.536797Z","iopub.status.idle":"2025-10-12T04:10:17.756848Z","shell.execute_reply.started":"2025-10-12T03:41:12.536773Z","shell.execute_reply":"2025-10-12T04:10:17.755854Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 5. Create submission.csv File ---\nsubmission_df = pd.DataFrame(all_preds, columns=LABELS)\nsubmission_df.insert(0, 'Image_name', all_img_names)\n\n# Ensure the order of rows matches the sample submission file\nsample_df = pd.read_csv(SAMPLE_SUBMISSION_PATH)\nsubmission_df = submission_df.set_index('Image_name').loc[sample_df['Image_name']].reset_index()\n\n# Save the final submission file\nsubmission_df.to_csv('submission.csv', index=False)\n\nprint(\"\\nSubmission file created successfully!\")\nprint(submission_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-12T04:10:17.758063Z","iopub.execute_input":"2025-10-12T04:10:17.758656Z","iopub.status.idle":"2025-10-12T04:10:18.65215Z","shell.execute_reply.started":"2025-10-12T04:10:17.758631Z","shell.execute_reply":"2025-10-12T04:10:18.651331Z"}},"outputs":[],"execution_count":null}]}