File size: 11,599 Bytes
a1ece17
 
 
 
19d498a
a1ece17
5fe67f2
a1ece17
 
 
d64050c
 
55abd01
 
 
 
 
 
 
 
 
a1ece17
 
55abd01
 
19d498a
55abd01
0bbec58
 
 
 
 
 
19d498a
0bbec58
 
 
55abd01
 
 
 
 
 
 
 
19d498a
55abd01
0bbec58
 
 
 
 
 
 
 
 
 
 
 
 
 
55abd01
 
 
 
 
 
 
 
 
 
 
19d498a
55abd01
0bbec58
 
 
 
 
 
 
19d498a
0bbec58
 
 
 
55abd01
 
 
 
 
8e35bc7
55abd01
 
 
 
 
 
 
 
 
 
 
 
19d498a
55abd01
 
 
 
 
 
 
 
 
 
 
 
 
 
19d498a
8e35bc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19d498a
55abd01
 
 
 
 
8e35bc7
 
 
 
 
 
55abd01
19d498a
55abd01
 
 
 
19d498a
55abd01
 
 
5993d2f
 
056ab4f
55abd01
 
 
 
19d498a
55abd01
b85505a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55abd01
5993d2f
 
55abd01
5993d2f
55abd01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e35bc7
55abd01
 
 
 
b85505a
53075d2
 
 
 
 
c004d97
55abd01
b85505a
 
55abd01
 
 
0bbec58
53075d2
 
 
 
 
48f5984
0bbec58
48f5984
 
 
0bbec58
b85505a
53075d2
 
 
 
 
0bbec58
 
 
 
 
8e35bc7
b85505a
0bbec58
 
 
 
8e35bc7
0bbec58
a1ece17
 
 
 
48f5984
a1ece17
d64050c
a1ece17
 
d64050c
 
 
 
 
 
a1ece17
d64050c
 
5fe67f2
a1ece17
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "import torch.nn.functional as F\n",
    "from datasets import load_dataset\n",
    "import fastcore.all as fc\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "import torchvision.transforms.functional as TF\n",
    "from torch.utils.data import default_collate, DataLoader\n",
    "import torch.optim as optim\n",
    "import pickle\n",
    "%matplotlib inline\n",
    "plt.rcParams['figure.figsize'] = [2, 2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset mnist (/Users/arun/.cache/huggingface/datasets/mnist/mnist/1.0.0/9d494b7f466d6931c64fb39d58bb1249a4d85c9eb9865d9bc20960b999e2a332)\n",
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 2/2 [00:00<00:00, 35.54it/s]\n"
     ]
    }
   ],
   "source": [
    "dataset_nm = 'mnist'\n",
    "x,y = 'image', 'label'\n",
    "ds = load_dataset(dataset_nm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAI4AAACOCAYAAADn/TAIAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkTPAAAACXBIWXMAAAsTAAALEwEAmpwYAAAIsUlEQVR4nO3df2yU9R0H8PfHtrQroFJBVrGjHVRAweHWCASCJBuumiXOLAyYWTbjQiYy58Y2fmzZ5oILJgsJMjSRrCsmig7mAjFsZBIlLkNGdeBgrOWnWqnFwkDmUNrrZ3/0bPu59cfTz3P33NPr+5WQu89zd32+MW+/z/eeu+dzoqogGqgrsj0AGpwYHHJhcMiFwSEXBodcGBxyCRUcEakWkXoROSYiK9M1KIo/8Z7HEZE8AA0A5gNoBLAfwGJV/Wf6hkdxlR/itbcCOKaqJwBARJ4FcBeAXoMzTAq1CMND7JKidhH/blHVManbwwRnHIC3u9WNAGb09YIiDMcM+XyIXVLUXtRtb/a0PUxwpIdt/3fcE5ElAJYAQBGKQ+yO4iTM4rgRQFm3+noAp1OfpKpPqmqVqlYVoDDE7ihOwgRnP4BKEakQkWEAFgHYkZ5hUdy5D1Wq2iYiywDsApAHoEZVD6dtZBRrYdY4UNWdAHamaSw0iPDMMbkwOOTC4JALg0MuDA65MDjkwuCQC4NDLgwOuTA45MLgkAuDQy6hPuQcSiTf/qfKGzM68Gvrf1Bu6kRxu6nHTzhj6uKl9jty764bZurXq54zdUviA1PP2Lq88/7E778aeJwDwRmHXBgccmFwyGXIrHHyplSaWgsLTH36tqtNfWmmXTeUXGXrVz5j1xlh/PG/I0396K+rTb1v2jOmPtl6ydRrm+eb+rpXMt/ziDMOuTA45MLgkEvOrnES8z5r6nW1G019Q4E9NxKlVk2Y+qcbv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Z45Jh+eOSYXBodcGBxyYXDIhcEhFwaHXBgccmFwyOV/atVD7hyCzrEAAAAASUVORK5CYII=",
      "text/plain": [
       "<Figure size 144x144 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def transform_ds(b):\n",
    "    b[x] = [TF.to_tensor(ele) for ele in b[x]]\n",
    "    return b\n",
    "\n",
    "dst = ds.with_transform(transform_ds)\n",
    "plt.imshow(dst['train'][0]['image'].permute(1,2,0));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([1024, 1, 28, 28]), torch.Size([1024]))"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bs = 1024\n",
    "class DataLoaders:\n",
    "    def __init__(self, train_ds, valid_ds, bs, collate_fn, **kwargs):\n",
    "        self.train = DataLoader(train_ds, batch_size=bs, shuffle=True, collate_fn=collate_fn, **kwargs)\n",
    "        self.valid = DataLoader(valid_ds, batch_size=bs*2, shuffle=False, collate_fn=collate_fn, **kwargs)\n",
    "\n",
    "def collate_fn(b):\n",
    "    collate = default_collate(b)\n",
    "    return (collate[x], collate[y])\n",
    "\n",
    "dls = DataLoaders(dst['train'], dst['test'], bs=bs, collate_fn=collate_fn)\n",
    "xb,yb = next(iter(dls.train))\n",
    "xb.shape, yb.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Reshape(nn.Module):\n",
    "    def __init__(self, dim):\n",
    "        super().__init__()\n",
    "        self.dim = dim\n",
    "    \n",
    "    def forward(self, x):\n",
    "        return x.reshape(self.dim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [],
   "source": [
    "def conv(ni, nf, ks=3, s=2, act=nn.ReLU, norm=None):\n",
    "    layers = [nn.Conv2d(ni, nf, kernel_size=ks, stride=s, padding=ks//2)]\n",
    "    if norm:\n",
    "        layers.append(norm)\n",
    "    if act:\n",
    "        layers.append(act())\n",
    "    return nn.Sequential(*layers)\n",
    "\n",
    "def _conv_block(ni, nf, ks=3, s=2, act=nn.ReLU, norm=None):\n",
    "    return nn.Sequential(\n",
    "        conv(ni, nf, ks=ks, s=1, norm=norm, act=act),\n",
    "        conv(nf, nf, ks=ks, s=s, norm=norm, act=act),\n",
    "    )\n",
    "\n",
    "class ResBlock(nn.Module):\n",
    "    def __init__(self, ni, nf, s=2, ks=3, act=nn.ReLU, norm=None):\n",
    "        super().__init__()\n",
    "        self.convs = _conv_block(ni, nf, s=s, ks=ks, act=act, norm=norm)\n",
    "        self.idconv = fc.noop if ni==nf else conv(ni, nf, ks=1, s=1, act=None)\n",
    "        self.pool = fc.noop if s==1 else nn.AvgPool2d(2, ceil_mode=True)\n",
    "        self.act = act()\n",
    "    \n",
    "    def forward(self, x):\n",
    "        return self.act(self.convs(x) + self.idconv(self.pool(x)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cnn_classifier():\n",
    "    return nn.Sequential(\n",
    "        ResBlock(1, 8, norm=nn.BatchNorm2d(8)),\n",
    "        ResBlock(8, 16, norm=nn.BatchNorm2d(16)),\n",
    "        ResBlock(16, 32, norm=nn.BatchNorm2d(32)),\n",
    "        ResBlock(32, 64, norm=nn.BatchNorm2d(64)),\n",
    "        ResBlock(64, 64, norm=nn.BatchNorm2d(64)),\n",
    "        conv(64, 10, act=False),\n",
    "        nn.Flatten(),\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [],
   "source": [
    "def kaiming_init(m):\n",
    "    if isinstance(m, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):\n",
    "        nn.init.kaiming_normal_(m.weight)        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train, epoch:1, loss: 0.1077, accuracy: 0.9104\n",
      "eval, epoch:1, loss: 0.0382, accuracy: 0.9791\n",
      "train, epoch:2, loss: 0.0410, accuracy: 0.9832\n",
      "eval, epoch:2, loss: 0.0221, accuracy: 0.9866\n",
      "train, epoch:3, loss: 0.0538, accuracy: 0.9871\n",
      "eval, epoch:3, loss: 0.0141, accuracy: 0.9887\n",
      "train, epoch:4, loss: 0.0343, accuracy: 0.9858\n",
      "eval, epoch:4, loss: 0.0163, accuracy: 0.9871\n",
      "train, epoch:5, loss: 0.0390, accuracy: 0.9865\n",
      "eval, epoch:5, loss: 0.0169, accuracy: 0.9871\n"
     ]
    }
   ],
   "source": [
    "model = cnn_classifier()\n",
    "model.apply(kaiming_init)\n",
    "lr = 0.1\n",
    "max_lr = 0.3\n",
    "epochs = 5\n",
    "opt = optim.AdamW(model.parameters(), lr=lr)\n",
    "sched = optim.lr_scheduler.OneCycleLR(opt, max_lr, total_steps=len(dls.train), epochs=epochs)\n",
    "for epoch in range(epochs):\n",
    "    for train in (True, False):\n",
    "        accuracy = 0\n",
    "        dl = dls.train if train else dls.valid\n",
    "        for xb,yb in dl:\n",
    "            preds = model(xb)\n",
    "            loss = F.cross_entropy(preds, yb)\n",
    "            if train:\n",
    "                loss.backward()\n",
    "                opt.step()\n",
    "                opt.zero_grad()\n",
    "            with torch.no_grad():\n",
    "                accuracy += (preds.argmax(1).detach().cpu() == yb).float().mean()\n",
    "        if train:\n",
    "            sched.step()\n",
    "        accuracy /= len(dl)\n",
    "        print(f\"{'train' if train else 'eval'}, epoch:{epoch+1}, loss: {loss.item():.4f}, accuracy: {accuracy:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {
    "tags": [
     "exclude"
    ]
   },
   "outputs": [],
   "source": [
    "with open('./classifier.pkl', 'wb') as model_file:\n",
    "    pickle.dump(model, model_file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": [
     "exclude"
    ]
   },
   "source": [
    "#### commit to .py file for deployment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {
    "tags": [
     "exclude"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[NbConvertApp] Converting notebook mnist_classifier.ipynb to script\n",
      "[NbConvertApp] Writing 3691 bytes to mnist_classifier.py\n"
     ]
    }
   ],
   "source": [
    "!jupyter nbconvert --to script --TagRemovePreprocessor.remove_cell_tags=\"exclude\" --TemplateExporter.exclude_input_prompt=True mnist_classifier.ipynb\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python_main",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}