-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
181 lines (146 loc) · 5.32 KB
/
main.py
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
# ================================================================ #
# Import Libraries #
# ================================================================ #
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt
# Hyper parameters
batch_size = 64
epochs = 5
# ================================================================ #
# Load Data #
# ================================================================ #
train_data = datasets.FashionMNIST(
root='data',
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root='data',
train=False,
download=True,
transform=ToTensor()
)
# ================================================================ #
# Create Data Loaders #
# ================================================================ #
train_dataloader = DataLoader(
dataset=train_data,
batch_size=batch_size,
shuffle=True
)
test_dataloader = DataLoader(
dataset=test_data,
batch_size=batch_size,
shuffle=False)
for images, labels in test_dataloader:
print('Shape of X [N, C, H, W]:', images.size())
print('Shape of y:', labels.size())
break
"""Result:
Shape of X [N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of y: torch.Size([64]) torch.int64
"""
# ================================================================ #
# Creating Models #
# ================================================================ #
# Get cpu, gpu or mps device for training.
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f'Using {device} device')
# Define model
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
# ================================================================ #
# Optimizing the Model Parameters #
# ================================================================ #
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
print(optimizer)
# ================================================================ #
# Train the Model #
# ================================================================ #
size = len(train_dataloader.dataset)
for epoch in range(epochs):
print(f"Epoch {epoch + 1}\n-------------------------------")
for i, (images, labels) in enumerate(train_dataloader):
images, labels = images.to(device), labels.to(device)
# Compute prediction error
outputs = model(images)
loss = loss_fn(outputs, labels)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
loss, current = loss.item(), i * len(images)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
# ================================================================ #
# Test the Model #
# ================================================================ #
size = len(test_dataloader.dataset)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for images, labels in test_dataloader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
test_loss += loss_fn(outputs, labels).item()
_, predictions = torch.max(outputs.data, 1)
correct += (predictions == labels).sum().item()
test_loss = test_loss / size
correct = correct / size
print(f"Test Error: \n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
# ================================================================ #
# Saving Models #
# ================================================================ #
torch.save(model.state_dict(), "model.pt")
print("Saved PyTorch Model State to model.pt")
# ================================================================ #
# Loading Models and Using #
# ================================================================ #
model = NeuralNetwork()
model.load_state_dict(torch.load("model.pt"))
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot",
]
model.eval()
image, label = test_data[0][0], test_data[0][1]
with torch.no_grad():
predictions = model(image)
predicted, actual = classes[predictions[0].argmax(0)], classes[label]
print(f'Predicted: "{predicted}", Actual: "{actual}"')