{ "cells": [ { "cell_type": "markdown", "id": "04210b87", "metadata": {}, "source": [ "# Testing the saved model\n", "One cell code from ChatGPT." ] }, { "cell_type": "code", "execution_count": 25, "id": "839c1262", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Prediction: ai\n", "Confidence: 0.7520\n" ] } ], "source": [ "import torch\n", "import torch.nn as nn\n", "import torchvision\n", "from PIL import Image\n", "import os\n", "\n", "# ----------------------------\n", "# 1️⃣ Device\n", "# ----------------------------\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# ----------------------------\n", "# 2️⃣ Recreate Model Architecture\n", "# ----------------------------\n", "weights = torchvision.models.EfficientNet_B0_Weights.DEFAULT\n", "model = torchvision.models.efficientnet_b0(weights=None).to(device)\n", "\n", "# IMPORTANT: Must match training classes\n", "class_names = [\"ai\", \"real\"] # or manually define list\n", "output_shape = 2\n", "\n", "model.classifier = nn.Sequential(\n", " nn.Dropout(p=0.2, inplace=True),\n", " nn.Linear(1280, output_shape, bias=True)\n", ").to(device)\n", "\n", "# ----------------------------\n", "# 3️⃣ Load Saved Weights\n", "# ----------------------------\n", "model.load_state_dict(torch.load(\"models/veriface_v2.pth\", map_location=device))\n", "model.eval()\n", "\n", "# ----------------------------\n", "# 4️⃣ Image Transforms (same as training)\n", "# ----------------------------\n", "auto_transforms = weights.transforms()\n", "\n", "# ----------------------------\n", "# 5️⃣ Prediction Function\n", "# ----------------------------\n", "def predict_image(image_path):\n", " image = Image.open(image_path).convert(\"RGB\")\n", " image = auto_transforms(image).unsqueeze(0).to(device)\n", "\n", " with torch.no_grad():\n", " outputs = model(image)\n", " probs = torch.softmax(outputs, dim=1)\n", " pred_class = torch.argmax(probs, dim=1).item()\n", "\n", " return class_names[pred_class], probs[0][pred_class].item()\n", "\n", "# ----------------------------\n", "# 6️⃣ Use It\n", "# ----------------------------\n", "# image_path = os.path.join(\"dataset\",\"test_data_v2\",\"5c30ab9ee1a34b5889c55619fc713338.jpg\")\n", "image_path = os.path.join(\"C:/Users/a/Downloads/sample7.jpg\")\n", "label, confidence = predict_image(image_path)\n", "\n", "print(f\"Prediction: {label}\")\n", "print(f\"Confidence: {confidence:.4f}\")" ] } ], "metadata": { "kernelspec": { "display_name": "myenv", "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.14.2" } }, "nbformat": 4, "nbformat_minor": 5 }