File size: 6,964 Bytes
8407327 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_312819/875621319.py:45: 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",
" checkpoint = torch.load(checkpoint_path)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Predictions:\n",
"n02105412: 26.26%\n",
"n02106662: 14.42%\n",
"n02099601: 8.62%\n",
"n02105162: 7.17%\n",
"n02105251: 3.21%\n"
]
},
{
"data": {
"text/plain": [
"(tensor([0.2626, 0.1442, 0.0862, 0.0717, 0.0321], device='cuda:0'),\n",
" tensor([227, 235, 207, 225, 226], device='cuda:0'))"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import torch\n",
"import torchvision.transforms as transforms\n",
"from torchvision.datasets import ImageFolder\n",
"from PIL import Image\n",
"import os\n",
"\n",
"# Define the device\n",
"device = (\n",
" \"cuda\"\n",
" if torch.cuda.is_available()\n",
" else \"mps\"\n",
" if torch.backends.mps.is_available()\n",
" else \"cpu\"\n",
")\n",
"\n",
"class Params:\n",
" def __init__(self):\n",
" self.batch_size = 512\n",
" self.name = \"resnet_50\"\n",
" self.workers = 16\n",
" self.lr = 0.1\n",
" self.momentum = 0.9\n",
" self.weight_decay = 1e-4\n",
" self.lr_step_size = 30\n",
" self.lr_gamma = 0.1\n",
"\n",
" def __repr__(self):\n",
" return str(self.__dict__)\n",
" \n",
" def __eq__(self, other):\n",
" return self.__dict__ == other.__dict__\n",
" \n",
"params = Params()\n",
"\n",
"# Path to the saved model checkpoint\n",
"checkpoint_path = \"checkpoints/resnet_50/checkpoint.pth\"\n",
"\n",
"# Load the model architecture\n",
"from model import ResNet50 # Assuming resnet.py contains your model definition\n",
"\n",
"num_classes = 1000 # Adjust this to match your dataset\n",
"model = ResNet50(num_classes=num_classes).to(device)\n",
"\n",
"# Load the trained model weights\n",
"checkpoint = torch.load(checkpoint_path)\n",
"model.load_state_dict(checkpoint[\"model\"])\n",
"\n",
"model.eval()\n",
"\n",
"# Define transformations for inference\n",
"inference_transforms = transforms.Compose([\n",
" transforms.ToTensor(),\n",
" transforms.Resize(size=256),\n",
" transforms.CenterCrop(224),\n",
" transforms.Normalize(mean=[0.485, 0.485, 0.406], std=[0.229, 0.224, 0.225]),\n",
"])\n",
"\n",
"# Function to make predictions on a single image\n",
"def predict(image_path, model, transforms, class_names=None):\n",
" # Load and transform the image\n",
" image = Image.open(image_path).convert(\"RGB\")\n",
" image_tensor = transforms(image).unsqueeze(0).to(device)\n",
"\n",
" # Forward pass\n",
" with torch.no_grad():\n",
" output = model(image_tensor)\n",
" probabilities = torch.nn.functional.softmax(output[0], dim=0)\n",
" top_prob, top_class = probabilities.topk(5, largest=True, sorted=True)\n",
"\n",
" # Display the top predictions\n",
" print(\"Predictions:\")\n",
" for i in range(top_prob.size(0)):\n",
" class_name = class_names[top_class[i]] if class_names else f\"Class {top_class[i].item()}\"\n",
" print(f\"{class_name}: {top_prob[i].item() * 100:.2f}%\")\n",
"\n",
" return top_prob, top_class\n",
"\n",
"# Define the dataset class names if available (optional)\n",
"# Example: Load class names from the training dataset folder\n",
"dataset_path = 'Imagenet/ILSVRC/Data/CLS-LOC/train'\n",
"class_names = sorted(os.listdir(dataset_path))\n",
"\n",
"# Path to the image for inference\n",
"image_path = \"dog.png\" # Replace with the actual path to your test image\n",
"\n",
"# Make a prediction\n",
"predict(image_path, model, inference_transforms, class_names=class_names)\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Predictions:\n",
"kelpie: 26.26%\n",
"German shepherd, German shepherd dog, German police dog, alsatian: 14.42%\n",
"golden retriever: 8.62%\n",
"malinois: 7.17%\n",
"briard: 3.21%\n"
]
}
],
"source": [
"# Path to the class mapping text file\n",
"class_mapping_file = \"Imagenet/LOC_synset_mapping.txt\" # Replace with the actual path\n",
"\n",
"# Read the file and create a mapping\n",
"id_to_name = {}\n",
"with open(class_mapping_file, 'r') as f:\n",
" for line in f:\n",
" class_id, class_name = line.strip().split(\" \", 1)\n",
" id_to_name[class_id] = class_name\n",
"\n",
"# Model output (example)\n",
"predicted_ids = [\"n02105412\", \"n02106662\", \"n02099601\", \"n02105162\", \"n02105251\"]\n",
"probabilities = [26.26, 14.42, 8.62, 7.17, 3.21]\n",
"\n",
"# Map the IDs to their names\n",
"predicted_names = [id_to_name[class_id] for class_id in predicted_ids]\n",
"\n",
"# Display the predictions\n",
"print(\"Predictions:\")\n",
"for prob, name in zip(probabilities, predicted_names):\n",
" print(f\"{name}: {prob:.2f}%\")\n"
]
}
],
"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
}
|