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
| import torch from torch import nn import torchvision from torchvision import transforms
mnist_train = torchvision.datasets.FashionMNIST( root='../data', train=True, transform=transforms.ToTensor(), download=True ) mnist_test = torchvision.datasets.FashionMNIST( root='../data', train=False, transform=transforms.ToTensor(), download=True )
class CnnNet(nn.Module): def __init__(self, input_channels=1) -> None: super().__init__() self.is_training = True self.drop_layer = nn.Dropout(0.5) self.conn2d1 = nn.Sequential( nn.Conv2d(1, 16, kernel_size=(3,3), stride=1, padding=1), nn.MaxPool2d(kernel_size=(2,2), stride=2), nn.BatchNorm2d(16), nn.ReLU() ) self.conn2d2 = nn.Sequential( nn.Conv2d(16, 32, kernel_size=(5,5), stride=1, padding=1), nn.MaxPool2d(kernel_size=(2,2), stride=2), nn.BatchNorm2d(32), nn.ReLU() ) self.conn2d3 = nn.Sequential( nn.Conv2d(32, 64, kernel_size=(5,5), stride=1, padding=1), nn.MaxPool2d(kernel_size=(2,2), stride=2), nn.BatchNorm2d(64), nn.ReLU() ) self.conn2d4 = nn.Sequential( nn.Conv2d(64, 128, kernel_size=(2,2), stride=1, padding=1), nn.BatchNorm2d(128), nn.ReLU() ) self.flatten = nn.Flatten() self.relu = nn.ReLU() self.line1 = nn.Linear(1152, 256) self.line2 = nn.Linear(256, 10)
def forward(self, x): c1 = self.conn2d1(x) c2 = self.conn2d2(c1) c3 = self.conn2d3(c2) c4 = self.conn2d4(c3) o1 = self.flatten(c4) l1 = self.relu(self.line1(o1)) if self.is_training: l1 = self.drop_layer(l1) o = self.line2(l1) return o
def predict(self, x): self.is_training = False o = self.forward(x) self.is_training = True return o
from torch.utils import data
def ac(data_iter, net, device): num_acs = [] for x, y in data_iter: x = x.to(device) y = y.to(device) y_hat = net.predict(x) maxs, indexs = torch.max(y_hat, dim=1) num_acs.append(y.eq(indexs).sum()/indexs.shape[0]) return sum(num_acs)/len(num_acs)
batch_size = 256 num_epochs = 20 lr = 0.1
train_iter = data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=4, pin_memory=True) test_iter = data.DataLoader(mnist_test, batch_size,shuffle=True, num_workers=4)
net = CnnNet() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net.to(device) loss = nn.CrossEntropyLoss() trainer = torch.optim.SGD(net.parameters(), lr=lr)
for i in range(num_epochs): for x,y in train_iter: x = x.to(device) y = y.to(device) y_hat = net(x) l = loss(y_hat, y) trainer.zero_grad() l.backward() trainer.step() print(l) print(ac(test_iter, net, device))
from torchinfo import summary
net = CnnNet() summary(net, input_size=(1,1,28,28))
========================================================================================== Layer (type:depth-idx) Output Shape Param ========================================================================================== CnnNet [1, 10] -- ├─Sequential: 1-1 [1, 16, 14, 14] -- │ └─Conv2d: 2-1 [1, 16, 28, 28] 160 │ └─MaxPool2d: 2-2 [1, 16, 14, 14] -- │ └─BatchNorm2d: 2-3 [1, 16, 14, 14] 32 │ └─ReLU: 2-4 [1, 16, 14, 14] -- ├─Sequential: 1-2 [1, 32, 6, 6] -- │ └─Conv2d: 2-5 [1, 32, 12, 12] 12,832 │ └─MaxPool2d: 2-6 [1, 32, 6, 6] -- │ └─BatchNorm2d: 2-7 [1, 32, 6, 6] 64 │ └─ReLU: 2-8 [1, 32, 6, 6] -- ├─Sequential: 1-3 [1, 64, 2, 2] -- │ └─Conv2d: 2-9 [1, 64, 4, 4] 51,264 │ └─MaxPool2d: 2-10 [1, 64, 2, 2] -- │ └─BatchNorm2d: 2-11 [1, 64, 2, 2] 128 │ └─ReLU: 2-12 [1, 64, 2, 2] -- ├─Sequential: 1-4 [1, 128, 3, 3] -- │ └─Conv2d: 2-13 [1, 128, 3, 3] 32,896 │ └─BatchNorm2d: 2-14 [1, 128, 3, 3] 256 │ └─ReLU: 2-15 [1, 128, 3, 3] -- ├─Flatten: 1-5 [1, 1152] -- ├─Linear: 1-6 [1, 256] 295,168 ├─ReLU: 1-7 [1, 256] -- ├─Dropout: 1-8 [1, 256] -- ├─Linear: 1-9 [1, 10] 2,570 ========================================================================================== Total params: 395,370 Trainable params: 395,370 Non-trainable params: 0 Total mult-adds (M): 3.39 ========================================================================================== Input size (MB): 0.00 Forward/backward pass size (MB): 0.20 Params size (MB): 1.58 Estimated Total Size (MB): 1.79 ==========================================================================================
|