File size: 6,985 Bytes
476e17d
abf3d6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476e17d
abf3d6a
 
 
 
 
 
 
 
 
 
 
 
 
476e17d
 
abf3d6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476e17d
 
abf3d6a
 
 
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
{
  "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
}