{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "8c0245a0-de56-4a1c-b541-9b47527b7954", "metadata": { "id": "8c0245a0-de56-4a1c-b541-9b47527b7954" }, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\n", "import torch.nn.functional as F\n", "import numpy as np\n", "import torchvision\n", "from torchvision import *\n", "from torch.utils.data import Dataset, DataLoader" ] }, { "cell_type": "code", "execution_count": null, "id": "611e56ee-6eeb-43d9-8cc1-fac6d35df9fb", "metadata": { "id": "611e56ee-6eeb-43d9-8cc1-fac6d35df9fb" }, "outputs": [], "source": [ "use_cuda = torch.cuda.is_available()\n", "device = torch.device('cuda:0' if use_cuda else 'cpu')\n", "criterion = nn.CrossEntropyLoss()" ] }, { "cell_type": "code", "execution_count": null, "id": "4faf2b2d-0f9e-4531-9d09-fd3975fd1df8", "metadata": { "id": "4faf2b2d-0f9e-4531-9d09-fd3975fd1df8" }, "outputs": [], "source": [ "transforms = transforms.Compose(\n", "[\n", " transforms.Resize((224, 224)),\n", " transforms.ToTensor()\n", "])" ] }, { "cell_type": "code", "execution_count": null, "id": "0eabaa23-bbd0-4f1e-b79d-22584f2ee8dd", "metadata": { "id": "0eabaa23-bbd0-4f1e-b79d-22584f2ee8dd" }, "outputs": [], "source": [ "# Create your dataset and dataloader here. Change the the dataset_path to refer to another folder.\n", "dataset_path = 'trainData'\n", "test_dataset = datasets.ImageFolder(root=dataset_path, transform=transforms)\n", "test_dataloader = DataLoader(test_dataset, batch_size=20, shuffle=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "fa642e6e-9f49-4e3d-b048-ea6a5d17e4a6", "metadata": { "scrolled": true, "id": "fa642e6e-9f49-4e3d-b048-ea6a5d17e4a6" }, "outputs": [], "source": [ "# Creates the model from the model weights and evaluates how well it does against the dataset\n", "def testModel(modelWeights):\n", " model = torchvision.models.resnet18(pretrained=False)\n", " num_ftrs = model.fc.in_features\n", " model.fc = nn.Linear(num_ftrs, 100)\n", " model.fc = model.fc.cuda()\n", "\n", " state_dict = torch.load(modelWeights)\n", " model.load_state_dict(state_dict)\n", " model = model.cuda()\n", " model.eval()\n", "\n", " batch_loss = 0\n", " total_t=0\n", " correct_t=0\n", "\n", " # Checks the prediction against the target for the whole dataset\n", " for data_t, target_t in (test_dataloader):\n", " data_t, target_t = data_t.to(device), target_t.to(device)\n", " outputs_t = model(data_t)\n", " loss_t = criterion(outputs_t, target_t)\n", " batch_loss += loss_t.item()\n", " _,pred_t = torch.max(outputs_t, dim=1)\n", " correct_t += torch.sum(pred_t==target_t).item()\n", " total_t += target_t.size(0)\n", " print('accuracy:',100 * correct_t/total_t)\n", " print('loss',batch_loss/len(test_dataloader))" ] }, { "cell_type": "code", "execution_count": null, "id": "0ce5bc24-57c5-4eb1-850e-fb4427210788", "metadata": { "id": "0ce5bc24-57c5-4eb1-850e-fb4427210788", "outputId": "6d972e75-aaec-47ef-fbea-9cae156d5a15" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/leistemb/.local/lib/python3.11/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.\n", " warnings.warn(\n", "/home/leistemb/.local/lib/python3.11/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=None`.\n", " warnings.warn(msg)\n", "/tmp/ipykernel_3348279/2814443803.py:7: 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", " state_dict = torch.load(modelWeights)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "accuracy: 86.8\n", "loss 0.7248420482873916\n" ] } ], "source": [ "# Run the actual test. Change the passed string to choose which model weights you want to use.\n", "testModel(\"modelWeights101\")" ] }, { "cell_type": "code", "execution_count": null, "id": "ef1439ca-f888-4be6-b35a-3241f0599e26", "metadata": { "id": "ef1439ca-f888-4be6-b35a-3241f0599e26" }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "e9123382-4570-4a7a-965e-e742e0326266", "metadata": { "id": "e9123382-4570-4a7a-965e-e742e0326266" }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.9" }, "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5 }