{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "device=\"cuda:0\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "\n", "class Bottleneck(nn.Module):\n", " expansion = 4\n", " def __init__(self, in_channels, out_channels, i_downsample=None, stride=1):\n", " super(Bottleneck, self).__init__()\n", " \n", " self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\n", " self.batch_norm1 = nn.BatchNorm2d(out_channels)\n", " \n", " self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1)\n", " self.batch_norm2 = nn.BatchNorm2d(out_channels)\n", " \n", " self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0)\n", " self.batch_norm3 = nn.BatchNorm2d(out_channels*self.expansion)\n", " \n", " self.i_downsample = i_downsample\n", " self.stride = stride\n", " self.relu = nn.ReLU()\n", " \n", " def forward(self, x):\n", " identity = x.clone()\n", " x = self.relu(self.batch_norm1(self.conv1(x)))\n", " \n", " x = self.relu(self.batch_norm2(self.conv2(x)))\n", " \n", " x = self.conv3(x)\n", " x = self.batch_norm3(x)\n", " \n", " #downsample if needed\n", " if self.i_downsample is not None:\n", " identity = self.i_downsample(identity)\n", " #add identity\n", " x+=identity\n", " x=self.relu(x)\n", " \n", " return x\n", "\n", "class Block(nn.Module):\n", " expansion = 1\n", " def __init__(self, in_channels, out_channels, i_downsample=None, stride=1):\n", " super(Block, self).__init__()\n", " \n", "\n", " self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False)\n", " self.batch_norm1 = nn.BatchNorm2d(out_channels)\n", " self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, stride=stride, bias=False)\n", " self.batch_norm2 = nn.BatchNorm2d(out_channels)\n", "\n", " self.i_downsample = i_downsample\n", " self.stride = stride\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " identity = x.clone()\n", "\n", " x = self.relu(self.batch_norm2(self.conv1(x)))\n", " x = self.batch_norm2(self.conv2(x))\n", "\n", " if self.i_downsample is not None:\n", " identity = self.i_downsample(identity)\n", " print(x.shape)\n", " print(identity.shape)\n", " x += identity\n", " x = self.relu(x)\n", " return x\n", "\n", "\n", " \n", " \n", "class ResNet(nn.Module):\n", " def __init__(self, ResBlock, layer_list, num_classes, num_channels=3):\n", " super(ResNet, self).__init__()\n", " self.in_channels = 64\n", " \n", " self.conv1 = nn.Conv2d(num_channels, 64, kernel_size=7, stride=2, padding=3, bias=False)\n", " self.batch_norm1 = nn.BatchNorm2d(64)\n", " self.relu = nn.ReLU()\n", " self.max_pool = nn.MaxPool2d(kernel_size = 3, stride=2, padding=1)\n", " \n", " self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64)\n", " self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2)\n", " self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2)\n", " self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2)\n", " \n", " self.avgpool = nn.AdaptiveAvgPool2d((1,1))\n", " self.fc = nn.Linear(512*ResBlock.expansion, num_classes)\n", " \n", " def forward(self, x):\n", " x = self.relu(self.batch_norm1(self.conv1(x)))\n", " x = self.max_pool(x)\n", "\n", " x = self.layer1(x)\n", " x = self.layer2(x)\n", " x = self.layer3(x)\n", " x = self.layer4(x)\n", " \n", " x = self.avgpool(x)\n", " x = x.reshape(x.shape[0], -1)\n", " x = self.fc(x)\n", " \n", " return x\n", " \n", " def _make_layer(self, ResBlock, blocks, planes, stride=1):\n", " ii_downsample = None\n", " layers = []\n", " \n", " if stride != 1 or self.in_channels != planes*ResBlock.expansion:\n", " ii_downsample = nn.Sequential(\n", " nn.Conv2d(self.in_channels, planes*ResBlock.expansion, kernel_size=1, stride=stride),\n", " nn.BatchNorm2d(planes*ResBlock.expansion)\n", " )\n", " \n", " layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride))\n", " self.in_channels = planes*ResBlock.expansion\n", " \n", " for i in range(blocks-1):\n", " layers.append(ResBlock(self.in_channels, planes))\n", " \n", " return nn.Sequential(*layers)\n", "\n", " \n", " \n", "def ResNet50(num_classes, channels=3):\n", " return ResNet(Bottleneck, [3,4,6,3], num_classes, channels)\n", " \n", "def ResNet101(num_classes, channels=3):\n", " return ResNet(Bottleneck, [3,4,23,3], num_classes, channels)\n", "\n", "def ResNet152(num_classes, channels=3):\n", " return ResNet(Bottleneck, [3,8,36,3], num_classes, channels)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "model = ResNet50(num_classes=1000).to(\"cuda:0\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_978058/872111556.py:6: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", " model.load_state_dict(torch.load('/home/jovyan/Tharun/Kaggle/resnet50_imagenet_bs64_ep120.pth')) # Path to your saved model\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Predicted class index: 339\n" ] } ], "source": [ "import torch\n", "from torchvision import models, transforms\n", "from PIL import Image\n", "\n", "# Load the saved model\n", "model.load_state_dict(torch.load('/home/jovyan/Tharun/Kaggle/resnet50_imagenet_bs64_ep120.pth')) # Path to your saved model\n", "model = model.to(\"cuda:0\") # Move model to the device (CPU or GPU)\n", "model.eval() # Set the model to evaluation mode\n", "\n", "# Preprocess the input image\n", "def preprocess_image(image_path):\n", " # Define the transformations to apply to the image\n", " transform = transforms.Compose([\n", " transforms.Resize(256), # Resize image to 256px\n", " transforms.CenterCrop(224), # Crop the center 224x224px\n", " transforms.ToTensor(), # Convert image to a tensor\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # Normalize\n", " ])\n", " \n", " # Load the image\n", " image = Image.open(image_path)\n", " \n", " # Ensure the image has 3 channels (RGB)\n", " image = image.convert(\"RGB\") # Convert image to RGB if it's not\n", " \n", " # Apply transformations\n", " image = transform(image)\n", " \n", " # Add batch dimension and move image to the appropriate device\n", " image = image.unsqueeze(0).to(device)\n", " \n", " return image\n", "\n", "# Function to make predictions\n", "def predict_image(image_path):\n", " image = preprocess_image(image_path) # Preprocess the input image\n", " \n", " # Forward pass to get predictions\n", " with torch.no_grad():\n", " outputs = model(image)\n", " \n", " # Get the predicted class index\n", " _, predicted_class = torch.max(outputs, 1)\n", " \n", " # Get the predicted class label (you should have a label-to-class mapping for ImageNet)\n", " predicted_class = predicted_class.item()\n", " \n", " # Optionally, if you have the ImageNet class labels, you can map the predicted index to a class name\n", " # Example: ImageNet class labels can be downloaded or are available in a text file\n", " return predicted_class\n", "\n", "# Path to the image you want to predict\n", "image_path = \"/home/jovyan/Tharun/Kaggle/gd-dog.jpg\" # Replace with your image path\n", "\n", "# Get the prediction\n", "predicted_class = predict_image(image_path)\n", "print(f\"Predicted class index: {predicted_class}\")\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Predicted class: sorrel\n" ] } ], "source": [ "# Assuming you have a list of ImageNet class labels (for example, `imagenet_classes` list)\n", "imagenet_classes = [line.strip() for line in open('/home/jovyan/Tharun/Kaggle/imagenet-classes.txt')] # Load class names from file\n", "\n", "# Get class name\n", "predicted_class_name = imagenet_classes[predicted_class]\n", "print(f\"Predicted class: {predicted_class_name}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "env", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }