{"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":"none","dataSources":[{"sourceId":11848,"databundleVersionId":862157,"sourceType":"competition"},{"sourceId":7054277,"sourceType":"datasetVersion","datasetId":4060134}],"dockerImageVersionId":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-26T04:12:57.627092Z","iopub.execute_input":"2023-11-26T04:12:57.627688Z","iopub.status.idle":"2023-11-26T04:12:59.418662Z","shell.execute_reply.started":"2023-11-26T04:12:57.627646Z","shell.execute_reply":"2023-11-26T04:12:59.417778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create the Net Class","metadata":{}},{"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self):\n        super(Net, self).__init__()\n        self.conv1 = nn.Conv2d(3, 6, 5)\n        self.pool = nn.MaxPool2d(2, 2)\n        self.conv2 = nn.Conv2d(6, 16, 5)\n        self.fc1 = nn.Linear(16 * 21 * 21, 120)\n        self.fc2 = nn.Linear(120, 84)\n        self.fc3 = nn.Linear(84, 2)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        x = x.view(-1, 16 * 21 * 21)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2023-11-26T04:12:59.420594Z","iopub.execute_input":"2023-11-26T04:12:59.421331Z","iopub.status.idle":"2023-11-26T04:12:59.428916Z","shell.execute_reply.started":"2023-11-26T04:12:59.421302Z","shell.execute_reply":"2023-11-26T04:12:59.427297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load the Model","metadata":{}},{"cell_type":"code","source":"model = Net()\nmodel.load_state_dict(torch.load('/kaggle/input/pytorch/model_pt (1).pth'))\nmodel.eval()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T04:12:59.430576Z","iopub.execute_input":"2023-11-26T04:12:59.430896Z","iopub.status.idle":"2023-11-26T04:12:59.464274Z","shell.execute_reply.started":"2023-11-26T04:12:59.430872Z","shell.execute_reply":"2023-11-26T04:12:59.463121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Preparing the Test Data","metadata":{}},{"cell_type":"code","source":"class HCDTestDataset(Dataset):\n    def __init__(self, csv_file, root_dir, transform=None):\n        self.test_frame = pd.read_csv(csv_file)\n        self.root_dir = root_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.test_frame)\n\n    def __getitem__(self, idx):\n        img_name = os.path.join(self.root_dir, self.test_frame.iloc[idx, 0] + '.tif')\n        image = Image.open(img_name)\n        \n        if self.transform:\n            image = self.transform(image)\n\n        return image\n\ntest_dir = '/kaggle/input/histopathologic-cancer-detection/test/'\ncsv_file = '/kaggle/input/histopathologic-cancer-detection/sample_submission.csv'\n\n# Transformations\ntransform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n])\n\n# Creating the dataset\ntest_dataset = HCDTestDataset(csv_file=csv_file, root_dir=test_dir, transform=transform)\n\n# Data Loader\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=0)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T04:12:59.466159Z","iopub.execute_input":"2023-11-26T04:12:59.466804Z","iopub.status.idle":"2023-11-26T04:12:59.521121Z","shell.execute_reply.started":"2023-11-26T04:12:59.466781Z","shell.execute_reply":"2023-11-26T04:12:59.51934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Making Predictions","metadata":{}},{"cell_type":"code","source":"# Collect all predictions here\npredictions = []\n\n# Disable gradient calculations\nwith torch.no_grad():\n    for inputs in test_loader:\n        outputs = model(inputs)\n        probs = F.softmax(outputs, dim=1)\n        preds = probs[:, 1]\n        predictions.extend(preds.tolist())\n\n# Update the submission DataFrame\nsubmission = pd.read_csv(csv_file)\nsubmission['label'] = predictions\nsubmission.to_csv('submission_pytorch.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T04:12:59.523225Z","iopub.execute_input":"2023-11-26T04:12:59.523581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"net = Net()\n\n# Load the saved model weights\nmodel_path = '/kaggle/input/pytorch'  # Adjust the path if necessary\ncnn =net.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))","metadata":{"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]}]}