File size: 11,458 Bytes
fc41719 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
{
"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
}
|