-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtorch-tc.py
More file actions
123 lines (107 loc) · 3.29 KB
/
torch-tc.py
File metadata and controls
123 lines (107 loc) · 3.29 KB
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
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, random_split
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.core.lightning import LightningModule
from torchmetrics import functional as FM
import matplotlib.pyplot as plt
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
train_dataset, val_dataset = random_split(training_data, [55000, 5000])
learning_rate = 1e-3
batch_size = 64
epochs = 10
train_dataloader = DataLoader(train_dataset, batch_size=batch_size)
val_dataloader = DataLoader(val_dataset, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
class LitModel(LightningModule):
def __init__(self):
super().__init__()
self.model = nn.Sequential(
nn.Flatten(),
nn.Linear(28*28, 512),
torch.nn.BatchNorm1d(512),
nn.ReLU(inplace=True),
nn.Linear(512, 256),
torch.nn.BatchNorm1d(256),
nn.ReLU(inplace=True),
nn.Linear(256, 64),
torch.nn.BatchNorm1d(64),
nn.ReLU(inplace=True),
nn.Linear(64, 10)
)
def forward(self, x):
return self.model(x)
def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
return loss
def validation_step(self, batch, batch_idx):
x, y = batch
logits = self(x)
acc = FM.accuracy(logits, y)
loss = F.cross_entropy(logits, y)
metrics = {'val_acc': acc, 'val_loss': loss}
self.log_dict(metrics)
def test_step(self, batch, batch_idx):
x, y = batch
logits = self(x)
acc = FM.accuracy(logits, y)
loss = F.cross_entropy(logits, y)
metrics = {'test_acc': acc, 'test_loss': loss}
self.log_dict(metrics)
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=learning_rate)
model = LitModel()
trainer = Trainer(max_epochs=epochs, gpus=0)
trainer.fit(model, train_dataloader, val_dataloader)
trainer.test(test_dataloaders=test_dataloader)
label_tags = {
0: 'T-Shirt',
1: 'Trouser',
2: 'Pullover',
3: 'Dress',
4: 'Coat',
5: 'Sandal',
6: 'Shirt',
7: 'Sneaker',
8: 'Bag',
9: 'Ankle Boot'
}
columns = 6
rows = 6
fig = plt.figure(figsize=(10,10))
model.eval()
for i in range(1, columns*rows+1):
data_idx = torch.randint(len(test_dataloader),(1,)).item()
input_img = test_data[data_idx][0].unsqueeze(dim=0)
output = model(input_img)
_, argmax = torch.max(output, 1)
pred = label_tags[argmax.item()]
label = label_tags[test_data[data_idx][1]]
fig.add_subplot(rows, columns, i)
if pred == label:
plt.title(pred)
cmap = 'Blues'
else:
plt.title(pred + '=>' + label)
cmap = 'Reds'
plot_img = test_data[data_idx][0][0,:,:]
plt.imshow(plot_img, cmap=cmap)
plt.axis('off')
plt.show()