File size: 13,573 Bytes
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Machine Learning\n",
    "\n",
    "This notebook is an example of a CNN for recognizing handwritten characters.\n",
    "\n",
    "Most of this code is from https://keras.io/examples/vision/mnist_convnet/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prepare the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x_train shape: (60000, 28, 28, 1)\n",
      "60000 train samples\n",
      "10000 test samples\n"
     ]
    }
   ],
   "source": [
    "# Model / data parameters\n",
    "num_classes = 10\n",
    "input_shape = (28, 28, 1)\n",
    "\n",
    "# Load the data and split it between train and test sets\n",
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "\n",
    "# Scale images to the [0, 1] range\n",
    "x_train = x_train.astype(\"float32\") / 255\n",
    "x_test = x_test.astype(\"float32\") / 255\n",
    "\n",
    "# Make sure images have shape (28, 28, 1)\n",
    "x_train = np.expand_dims(x_train, -1)\n",
    "x_test = np.expand_dims(x_test, -1)\n",
    "print(\"x_train shape:\", x_train.shape)\n",
    "print(x_train.shape[0], \"train samples\")\n",
    "print(x_test.shape[0], \"test samples\")\n",
    "\n",
    "\n",
    "# convert class vectors to binary class matrices\n",
    "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
    "y_test = keras.utils.to_categorical(y_test, num_classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build the Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " conv2d (Conv2D)             (None, 26, 26, 32)        320       \n",
      "                                                                 \n",
      " max_pooling2d (MaxPooling2D  (None, 13, 13, 32)       0         \n",
      " )                                                               \n",
      "                                                                 \n",
      " conv2d_1 (Conv2D)           (None, 11, 11, 64)        18496     \n",
      "                                                                 \n",
      " max_pooling2d_1 (MaxPooling  (None, 5, 5, 64)         0         \n",
      " 2D)                                                             \n",
      "                                                                 \n",
      " flatten (Flatten)           (None, 1600)              0         \n",
      "                                                                 \n",
      " dropout (Dropout)           (None, 1600)              0         \n",
      "                                                                 \n",
      " dense (Dense)               (None, 10)                16010     \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 34,826\n",
      "Trainable params: 34,826\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = keras.Sequential(\n",
    "    [\n",
    "        keras.Input(shape=input_shape),\n",
    "        layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\"),\n",
    "        layers.MaxPooling2D(pool_size=(2, 2)),\n",
    "        layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n",
    "        layers.MaxPooling2D(pool_size=(2, 2)),\n",
    "        layers.Flatten(),\n",
    "        layers.Dropout(0.5),\n",
    "        layers.Dense(num_classes, activation=\"softmax\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train the Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/15\n",
      "422/422 [==============================] - 6s 3ms/step - loss: 0.3744 - accuracy: 0.8868 - val_loss: 0.0892 - val_accuracy: 0.9763\n",
      "Epoch 2/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.1177 - accuracy: 0.9634 - val_loss: 0.0660 - val_accuracy: 0.9817\n",
      "Epoch 3/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0876 - accuracy: 0.9732 - val_loss: 0.0480 - val_accuracy: 0.9865\n",
      "Epoch 4/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0738 - accuracy: 0.9774 - val_loss: 0.0462 - val_accuracy: 0.9872\n",
      "Epoch 5/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0642 - accuracy: 0.9805 - val_loss: 0.0440 - val_accuracy: 0.9872\n",
      "Epoch 6/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0585 - accuracy: 0.9818 - val_loss: 0.0373 - val_accuracy: 0.9898\n",
      "Epoch 7/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0544 - accuracy: 0.9832 - val_loss: 0.0348 - val_accuracy: 0.9908\n",
      "Epoch 8/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0495 - accuracy: 0.9845 - val_loss: 0.0342 - val_accuracy: 0.9907\n",
      "Epoch 9/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0462 - accuracy: 0.9853 - val_loss: 0.0313 - val_accuracy: 0.9910\n",
      "Epoch 10/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0444 - accuracy: 0.9858 - val_loss: 0.0320 - val_accuracy: 0.9907\n",
      "Epoch 11/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0418 - accuracy: 0.9872 - val_loss: 0.0303 - val_accuracy: 0.9913\n",
      "Epoch 12/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0410 - accuracy: 0.9874 - val_loss: 0.0276 - val_accuracy: 0.9922\n",
      "Epoch 13/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0381 - accuracy: 0.9875 - val_loss: 0.0292 - val_accuracy: 0.9912\n",
      "Epoch 14/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0368 - accuracy: 0.9879 - val_loss: 0.0291 - val_accuracy: 0.9920\n",
      "Epoch 15/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0356 - accuracy: 0.9888 - val_loss: 0.0257 - val_accuracy: 0.9925\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x1c9d4871f40>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_size = 128\n",
    "epochs = 15\n",
    "\n",
    "model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
    "\n",
    "model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate the Trained Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test loss: 0.026043808087706566\n",
      "Test accuracy: 0.9907000064849854\n"
     ]
    }
   ],
   "source": [
    "score = model.evaluate(x_test, y_test, verbose=0)\n",
    "print(\"Test loss:\", score[0])\n",
    "print(\"Test accuracy:\", score[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save(\"mnist.h5\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example GUI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "from tkinter import *\n",
    "from PIL import ImageGrab\n",
    "import imageio\n",
    "import tkinter.font as font\n",
    "\n",
    "class Paint(object):\n",
    "    def __init__(self):\n",
    "        self.root=Tk()\n",
    "        self.root.title('Playing with numbers')\n",
    "        # self.root.wm_iconbitmap('44143.ico')\n",
    "        self.root.configure(background='light salmon')\n",
    "        self.c = Canvas(self.root,bg='light cyan', height=330, width=400)\n",
    "        self.label = Label(self.root, text='Draw any numer', font=20, bg='light salmon')\n",
    "        self.label.grid(row=0, column=3)\n",
    "        self.c.grid(row=1, columnspan=9)\n",
    "        self.c.create_line(0,0,400,0,width=20,fill='midnight blue')\n",
    "        self.c.create_line(0,0,0,330,width=20,fill='midnight blue')\n",
    "        self.c.create_line(400,0,400,330,width=20,fill='midnight blue')\n",
    "        self.c.create_line(0,330,400,330,width=20,fill='midnight blue')\n",
    "        self.myfont = font.Font(size=20,weight='bold')\n",
    "        self.predicting_button=Button(self.root,text='Predict', fg='white', bg='blue', height=2, width=6, font=self.myfont, command=lambda:self.classify(self.c))\n",
    "        self.predicting_button.grid(row=2,column=1)\n",
    "        self.clear=Button(self.root,text='Clear', fg='white', bg='orange', height=2, width=6, font=self.myfont, command=self.clear)\n",
    "        self.clear.grid(row=2,column=5)\n",
    "        self.prediction_text = Text(self.root, height=5, width=5)\n",
    "        self.prediction_text.grid(row=4, column=3)\n",
    "        self.label=Label(self.root, text=\"Predicted Number is\", fg=\"black\", font=30, bg='light salmon')\n",
    "\n",
    "        self.label.grid(row=3,column=3)\n",
    "        self.model=model\n",
    "        self.setup()\n",
    "        self.root.mainloop()\n",
    "\n",
    "\n",
    "    def setup(self):\n",
    "        self.old_x=None\n",
    "        self.old_y=None\n",
    "        self.color='black'\n",
    "        self.linewidth=15\n",
    "        self.c.bind('<B1-Motion>', self.paint)\n",
    "        self.c.bind('<ButtonRelease-1>', self.reset)\n",
    "\n",
    "\n",
    "    def paint(self,event):\n",
    "        paint_color=self.color\n",
    "        if self.old_x and self.old_y:\n",
    "            self.c.create_line(self.old_x,self.old_y,event.x,event.y,fill=paint_color,width=self.linewidth,capstyle=ROUND,\n",
    "                              smooth=TRUE,splinesteps=48)\n",
    "        self.old_x=event.x\n",
    "        self.old_y=event.y\n",
    "\n",
    "\n",
    "    def clear(self):\n",
    "        \"\"\"Clear drawing area\"\"\"\n",
    "        self.c.delete(\"all\")\n",
    "\n",
    "    def reset(self, event):\n",
    "        \"\"\"reset old_x and old_y if the left mouse button is released\"\"\"\n",
    "        self.old_x, self.old_y = None, None\n",
    "\n",
    "\n",
    "    def classify(self,widget):\n",
    "        x=self.root.winfo_rootx()+widget.winfo_x()\n",
    "        y=self.root.winfo_rooty()+widget.winfo_y()\n",
    "        x1=widget.winfo_width()\n",
    "        y1=widget.winfo_height()\n",
    "        ImageGrab.grab().crop((x,y,x1,y1)).resize((28,28)).save('classify.png')\n",
    "        img=imageio.imread('classify.png', as_gray=True, pilmode='P')\n",
    "        img=np.array(img)\n",
    "        img=np.reshape(img,(1,28,28,1))\n",
    "        img[img==0] = 255\n",
    "        img[img==225] = 0\n",
    "        # Predict digit\n",
    "        pred = self.model.predict([img])\n",
    "        # Get index with highest probability\n",
    "        pred = np.argmax(pred)\n",
    "        print(pred)\n",
    "        self.prediction_text.delete(\"1.0\", END)\n",
    "        self.prediction_text.insert(END, pred)\n",
    "        labelfont = ('times', 30, 'bold')\n",
    "        self.prediction_text.config(font=labelfont)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    Paint()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.7 ('base')",
   "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,
  "vscode": {
   "interpreter": {
    "hash": "ad2bdc8ecc057115af97d19610ffacc2b4e99fae6737bb82f5d7fb13d2f2c186"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}