JunyiGuan commited on
Commit
254c4fb
·
verified ·
1 Parent(s): 31409f6

Upload train.ipynb

Browse files
Files changed (1) hide show
  1. train.ipynb +173 -0
train.ipynb ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "### train a binary classifier for CIFAKE"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": null,
13
+ "metadata": {},
14
+ "outputs": [
15
+ {
16
+ "name": "stderr",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "d:\\Anaconda\\envs\\ai\\Lib\\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",
20
+ " warnings.warn(\n",
21
+ "d:\\Anaconda\\envs\\ai\\Lib\\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=VGG16_Weights.IMAGENET1K_V1`. You can also use `weights=VGG16_Weights.DEFAULT` to get the most up-to-date weights.\n",
22
+ " warnings.warn(msg)\n"
23
+ ]
24
+ },
25
+ {
26
+ "name": "stdout",
27
+ "output_type": "stream",
28
+ "text": [
29
+ "Epoch 1/10\n",
30
+ "Train Loss: 0.4615 Acc: 0.7786\n",
31
+ "Epoch 2/10\n",
32
+ "Train Loss: 0.3657 Acc: 0.8369\n",
33
+ "Epoch 3/10\n",
34
+ "Train Loss: 0.3367 Acc: 0.8522\n",
35
+ "Epoch 4/10\n",
36
+ "Train Loss: 0.3150 Acc: 0.8626\n",
37
+ "Epoch 5/10\n",
38
+ "Train Loss: 0.3046 Acc: 0.8680\n",
39
+ "Epoch 6/10\n",
40
+ "Train Loss: 0.2917 Acc: 0.8745\n",
41
+ "Epoch 7/10\n",
42
+ "Train Loss: 0.2805 Acc: 0.8809\n",
43
+ "Epoch 8/10\n",
44
+ "Train Loss: 0.2760 Acc: 0.8824\n",
45
+ "Epoch 9/10\n",
46
+ "Train Loss: 0.2714 Acc: 0.8843\n",
47
+ "Epoch 10/10\n",
48
+ "Train Loss: 0.2653 Acc: 0.8868\n",
49
+ "Model saved to vgg_model.pth\n",
50
+ "Test Accuracy: 0.8859\n",
51
+ "Final test accuracy: 0.8859\n"
52
+ ]
53
+ }
54
+ ],
55
+ "source": [
56
+ "import os\n",
57
+ "import torch\n",
58
+ "import torch.nn as nn\n",
59
+ "from torch.utils.data import DataLoader, random_split\n",
60
+ "from torchvision import datasets, models, transforms\n",
61
+ "\n",
62
+ "def train_and_save_vgg_model(data_dir, model_path, num_epochs=30, batch_size=32, lr=0.00001):\n",
63
+ " data_transform = transforms.Compose([\n",
64
+ " transforms.RandomResizedCrop(32),\n",
65
+ " transforms.RandomHorizontalFlip(),\n",
66
+ " transforms.RandomRotation(15),\n",
67
+ " transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3),\n",
68
+ " transforms.ToTensor(),\n",
69
+ " transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n",
70
+ " ])\n",
71
+ "\n",
72
+ " full_dataset = datasets.ImageFolder(data_dir, transform=data_transform)\n",
73
+ "\n",
74
+ " train_size = int(0.8 * len(full_dataset))\n",
75
+ " test_size = len(full_dataset) - train_size\n",
76
+ " train_dataset, test_dataset = random_split(full_dataset, [train_size, test_size])\n",
77
+ "\n",
78
+ " train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)\n",
79
+ " test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=4)\n",
80
+ "\n",
81
+ " device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
82
+ "\n",
83
+ " model = models.vgg16(pretrained=True)\n",
84
+ " for param in model.features.parameters(): \n",
85
+ " param.requires_grad = True\n",
86
+ " model.classifier[6] = nn.Linear(model.classifier[6].in_features, 2)\n",
87
+ " model = model.to(device)\n",
88
+ "\n",
89
+ " criterion = nn.CrossEntropyLoss()\n",
90
+ " optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n",
91
+ " scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n",
92
+ "\n",
93
+ " for epoch in range(num_epochs):\n",
94
+ " print(f\"Epoch {epoch + 1}/{num_epochs}\")\n",
95
+ " model.train()\n",
96
+ "\n",
97
+ " running_loss = 0.0\n",
98
+ " running_corrects = 0\n",
99
+ "\n",
100
+ " for inputs, labels in train_loader:\n",
101
+ " inputs, labels = inputs.to(device), labels.to(device)\n",
102
+ " optimizer.zero_grad()\n",
103
+ "\n",
104
+ " outputs = model(inputs)\n",
105
+ " loss = criterion(outputs, labels)\n",
106
+ " _, preds = torch.max(outputs, 1)\n",
107
+ "\n",
108
+ " loss.backward()\n",
109
+ " optimizer.step()\n",
110
+ "\n",
111
+ " running_loss += loss.item() * inputs.size(0)\n",
112
+ " running_corrects += torch.sum(preds == labels.data)\n",
113
+ "\n",
114
+ " epoch_loss = running_loss / train_size\n",
115
+ " epoch_acc = running_corrects.double() / train_size\n",
116
+ "\n",
117
+ " print(f\"Train Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}\")\n",
118
+ " scheduler.step()\n",
119
+ "\n",
120
+ " torch.save(model.state_dict(), model_path)\n",
121
+ " print(f\"Model saved to {model_path}\")\n",
122
+ "\n",
123
+ " model.eval()\n",
124
+ " test_corrects = 0\n",
125
+ "\n",
126
+ " with torch.no_grad():\n",
127
+ " for inputs, labels in test_loader:\n",
128
+ " inputs, labels = inputs.to(device), labels.to(device)\n",
129
+ "\n",
130
+ " outputs = model(inputs)\n",
131
+ " _, preds = torch.max(outputs, 1)\n",
132
+ " test_corrects += torch.sum(preds == labels.data)\n",
133
+ "\n",
134
+ " test_acc = test_corrects.double() / test_size\n",
135
+ " print(f\"Test Accuracy: {test_acc:.4f}\")\n",
136
+ "\n",
137
+ " return test_acc.item()\n",
138
+ "\n",
139
+ "\n",
140
+ "if __name__ == \"__main__\":\n",
141
+ " data_dir = \"CIFAKE/train\" \n",
142
+ " model_path = \"vgg_model.pth\"\n",
143
+ " num_epochs = 10\n",
144
+ " batch_size = 32\n",
145
+ " lr = 0.00001\n",
146
+ "\n",
147
+ " test_acc = train_and_save_vgg_model(data_dir, model_path, num_epochs, batch_size, lr)\n",
148
+ " print(f\"Final test accuracy: {test_acc:.4f}\")\n"
149
+ ]
150
+ }
151
+ ],
152
+ "metadata": {
153
+ "kernelspec": {
154
+ "display_name": "ai",
155
+ "language": "python",
156
+ "name": "python3"
157
+ },
158
+ "language_info": {
159
+ "codemirror_mode": {
160
+ "name": "ipython",
161
+ "version": 3
162
+ },
163
+ "file_extension": ".py",
164
+ "mimetype": "text/x-python",
165
+ "name": "python",
166
+ "nbconvert_exporter": "python",
167
+ "pygments_lexer": "ipython3",
168
+ "version": "3.12.2"
169
+ }
170
+ },
171
+ "nbformat": 4,
172
+ "nbformat_minor": 2
173
+ }