{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":10418,"databundleVersionId":862236,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport os\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom PIL import Image\nfrom torchvision import transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom tqdm import tqdm","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:52:04.192773Z","iopub.execute_input":"2024-05-19T05:52:04.193505Z","iopub.status.idle":"2024-05-19T05:52:12.651010Z","shell.execute_reply.started":"2024-05-19T05:52:04.193469Z","shell.execute_reply":"2024-05-19T05:52:12.650217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/human-protein-atlas-image-classification/train.csv')\nprint(f'Train set:\\n{data}')\n\ntrain_dir = '/kaggle/input/human-protein-atlas-image-classification/train'\nimg_list = os.listdir(train_dir)\n\n# sample\nimg_sample = os.path.join(train_dir, img_list[0])\n    \nimg = plt.imread(img_sample)\nplt.imshow(img)\n\nprint(img_list[:4])\n    \n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:52:23.532102Z","iopub.execute_input":"2024-05-19T05:52:23.532835Z","iopub.status.idle":"2024-05-19T05:52:27.177312Z","shell.execute_reply.started":"2024-05-19T05:52:23.532802Z","shell.execute_reply":"2024-05-19T05:52:27.176405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AtlasDataset(Dataset):\n    def __init__(self, csv_file, data_dir, transform=None):\n        self.data = pd.read_csv(csv_file)\n        self.data_dir = data_dir\n        self.transform = transform\n        self.num_classes = 28\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        img_id = self.data.iloc[idx, 0]\n        labels = self.data.iloc[idx, 1]\n        channels = []\n        for color in ['red', 'green', 'blue', 'yellow']:\n            image_path = os.path.join(self.data_dir, f\"{img_id}_{color}.png\")\n            image = Image.open(image_path)\n            channels.append(transforms.ToTensor()(image))\n\n        image = torch.cat(channels, dim=0)\n        if self.transform:\n            image = self.transform(image)\n        \n        labels_vector = torch.zeros(self.num_classes)\n        for label in labels.split():\n            labels_vector[int(label)] = 1\n        \n        return image, labels_vector\n    \ntransform = transforms.Compose([\ntransforms.Resize((224, 224), antialias=True),\ntransforms.Normalize(mean=[0.485, 0.456, 0.406, 0.485], std=[0.229, 0.224, 0.225, 0.229])\n])","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:53:36.659822Z","iopub.execute_input":"2024-05-19T05:53:36.660161Z","iopub.status.idle":"2024-05-19T05:53:36.670037Z","shell.execute_reply.started":"2024-05-19T05:53:36.660134Z","shell.execute_reply":"2024-05-19T05:53:36.669145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"csv_file = '/kaggle/input/human-protein-atlas-image-classification/train.csv'\ndata_dir = '/kaggle/input/human-protein-atlas-image-classification/train'\n\ndataset = AtlasDataset(csv_file,data_dir, transform=transform)\n\ntrain_data, test_data = random_split(dataset, (0.8, 0.2))\ntrain_loader = DataLoader(train_data, batch_size=32, shuffle=True)\ntest_loader = DataLoader(test_data, batch_size=32)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:53:41.621461Z","iopub.execute_input":"2024-05-19T05:53:41.622226Z","iopub.status.idle":"2024-05-19T05:53:41.682469Z","shell.execute_reply.started":"2024-05-19T05:53:41.622191Z","shell.execute_reply":"2024-05-19T05:53:41.681597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AtlasCNN(nn.Module):\n    def __init__(self, num_classes=28):\n        super(AtlasCNN, self).__init__()\n        self.conv1 = nn.Conv2d(4, 32, kernel_size=3, stride=1, padding=1)\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)\n        self.fc1 = nn.Linear(64 * 56 * 56, 512)\n        self.fc2 = nn.Linear(512, num_classes)\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, 64 * 56 * 56)\n        x = F.relu(self.fc1(x))\n        x = self.fc2(x)\n        return x\n\nmodel = AtlasCNN()\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:53:45.399523Z","iopub.execute_input":"2024-05-19T05:53:45.400227Z","iopub.status.idle":"2024-05-19T05:53:46.451447Z","shell.execute_reply.started":"2024-05-19T05:53:45.400193Z","shell.execute_reply":"2024-05-19T05:53:46.450442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"criterion = nn.BCEWithLogitsLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:53:51.599267Z","iopub.execute_input":"2024-05-19T05:53:51.599593Z","iopub.status.idle":"2024-05-19T05:53:51.604395Z","shell.execute_reply.started":"2024-05-19T05:53:51.599568Z","shell.execute_reply":"2024-05-19T05:53:51.603361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_epochs = 10\n\nfor epoch in tqdm(range(num_epochs)):\n    running_loss = 0.0\n    for inputs, labels in train_loader:\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        labels = labels.type(torch.FloatTensor)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        running_loss += loss.item()\n    torch.save(model.state_dict(), f'epoch_{epoch+1}_weights.pth')\n\n    \n    print(f\"Epoch {epoch+1}, Loss: {running_loss/len(train_loader)}\")","metadata":{"execution":{"iopub.status.busy":"2024-05-19T05:53:58.398359Z","iopub.execute_input":"2024-05-19T05:53:58.399180Z","iopub.status.idle":"2024-05-19T10:34:31.187398Z","shell.execute_reply.started":"2024-05-19T05:53:58.399148Z","shell.execute_reply":"2024-05-19T10:34:31.186123Z"},"trusted":true},"execution_count":null,"outputs":[]}]}