-
Notifications
You must be signed in to change notification settings - Fork 0
/
Train.py
48 lines (38 loc) · 1018 Bytes
/
Train.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
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from Model import CNN
batchSize = 4
transform = transforms.Compose([
transforms.ToTensor()
])
# Load train dataset
trainSet = torchvision.datasets.ImageFolder(
root = "./Dataset/Train/",
transform = transform
)
trainLoader = torch.utils.data.DataLoader(
trainSet,
batch_size = batchSize,
shuffle = True,
num_workers = 0
)
# Model training
epochs = 20
learningRate = 1e-4
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr = learningRate)
model.train()
for epoch in range(epochs):
for images, labels in trainLoader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f"[Epoch: {epoch + 1:5d}/{epochs}] Loss: {loss.item()}")
torch.save(model.state_dict(), "Model.pth")
print("Finished Training!")