Kyle Dampier commited on
Commit
e82c862
1 Parent(s): 1a84122

added training ipynb to my project

Browse files
Files changed (1) hide show
  1. Week1.ipynb +386 -0
Week1.ipynb ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Introduction to Machine Learning\n",
8
+ "\n",
9
+ "This notebook is an example of a CNN for recognizing handwritten characters.\n",
10
+ "\n",
11
+ "Most of this code is from https://keras.io/examples/vision/mnist_convnet/"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "markdown",
16
+ "metadata": {},
17
+ "source": [
18
+ "## Setup"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": 2,
24
+ "metadata": {},
25
+ "outputs": [],
26
+ "source": [
27
+ "import numpy as np\n",
28
+ "from tensorflow import keras\n",
29
+ "from tensorflow.keras import layers"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "metadata": {},
35
+ "source": [
36
+ "## Prepare the data"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "execution_count": 3,
42
+ "metadata": {},
43
+ "outputs": [
44
+ {
45
+ "name": "stdout",
46
+ "output_type": "stream",
47
+ "text": [
48
+ "x_train shape: (60000, 28, 28, 1)\n",
49
+ "60000 train samples\n",
50
+ "10000 test samples\n"
51
+ ]
52
+ }
53
+ ],
54
+ "source": [
55
+ "# Model / data parameters\n",
56
+ "num_classes = 10\n",
57
+ "input_shape = (28, 28, 1)\n",
58
+ "\n",
59
+ "# Load the data and split it between train and test sets\n",
60
+ "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
61
+ "\n",
62
+ "# Scale images to the [0, 1] range\n",
63
+ "x_train = x_train.astype(\"float32\") / 255\n",
64
+ "x_test = x_test.astype(\"float32\") / 255\n",
65
+ "\n",
66
+ "# Make sure images have shape (28, 28, 1)\n",
67
+ "x_train = np.expand_dims(x_train, -1)\n",
68
+ "x_test = np.expand_dims(x_test, -1)\n",
69
+ "print(\"x_train shape:\", x_train.shape)\n",
70
+ "print(x_train.shape[0], \"train samples\")\n",
71
+ "print(x_test.shape[0], \"test samples\")\n",
72
+ "\n",
73
+ "\n",
74
+ "# convert class vectors to binary class matrices\n",
75
+ "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
76
+ "y_test = keras.utils.to_categorical(y_test, num_classes)"
77
+ ]
78
+ },
79
+ {
80
+ "cell_type": "markdown",
81
+ "metadata": {},
82
+ "source": [
83
+ "## Build the Model"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": 4,
89
+ "metadata": {},
90
+ "outputs": [
91
+ {
92
+ "name": "stdout",
93
+ "output_type": "stream",
94
+ "text": [
95
+ "Model: \"sequential\"\n",
96
+ "_________________________________________________________________\n",
97
+ " Layer (type) Output Shape Param # \n",
98
+ "=================================================================\n",
99
+ " conv2d (Conv2D) (None, 26, 26, 32) 320 \n",
100
+ " \n",
101
+ " max_pooling2d (MaxPooling2D (None, 13, 13, 32) 0 \n",
102
+ " ) \n",
103
+ " \n",
104
+ " conv2d_1 (Conv2D) (None, 11, 11, 64) 18496 \n",
105
+ " \n",
106
+ " max_pooling2d_1 (MaxPooling (None, 5, 5, 64) 0 \n",
107
+ " 2D) \n",
108
+ " \n",
109
+ " flatten (Flatten) (None, 1600) 0 \n",
110
+ " \n",
111
+ " dropout (Dropout) (None, 1600) 0 \n",
112
+ " \n",
113
+ " dense (Dense) (None, 10) 16010 \n",
114
+ " \n",
115
+ "=================================================================\n",
116
+ "Total params: 34,826\n",
117
+ "Trainable params: 34,826\n",
118
+ "Non-trainable params: 0\n",
119
+ "_________________________________________________________________\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "model = keras.Sequential(\n",
125
+ " [\n",
126
+ " keras.Input(shape=input_shape),\n",
127
+ " layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\"),\n",
128
+ " layers.MaxPooling2D(pool_size=(2, 2)),\n",
129
+ " layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n",
130
+ " layers.MaxPooling2D(pool_size=(2, 2)),\n",
131
+ " layers.Flatten(),\n",
132
+ " layers.Dropout(0.5),\n",
133
+ " layers.Dense(num_classes, activation=\"softmax\"),\n",
134
+ " ]\n",
135
+ ")\n",
136
+ "\n",
137
+ "model.summary()"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "markdown",
142
+ "metadata": {},
143
+ "source": [
144
+ "## Train the Model"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "execution_count": 5,
150
+ "metadata": {},
151
+ "outputs": [
152
+ {
153
+ "name": "stdout",
154
+ "output_type": "stream",
155
+ "text": [
156
+ "Epoch 1/15\n",
157
+ "422/422 [==============================] - 6s 3ms/step - loss: 0.3744 - accuracy: 0.8868 - val_loss: 0.0892 - val_accuracy: 0.9763\n",
158
+ "Epoch 2/15\n",
159
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.1177 - accuracy: 0.9634 - val_loss: 0.0660 - val_accuracy: 0.9817\n",
160
+ "Epoch 3/15\n",
161
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0876 - accuracy: 0.9732 - val_loss: 0.0480 - val_accuracy: 0.9865\n",
162
+ "Epoch 4/15\n",
163
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0738 - accuracy: 0.9774 - val_loss: 0.0462 - val_accuracy: 0.9872\n",
164
+ "Epoch 5/15\n",
165
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0642 - accuracy: 0.9805 - val_loss: 0.0440 - val_accuracy: 0.9872\n",
166
+ "Epoch 6/15\n",
167
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0585 - accuracy: 0.9818 - val_loss: 0.0373 - val_accuracy: 0.9898\n",
168
+ "Epoch 7/15\n",
169
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0544 - accuracy: 0.9832 - val_loss: 0.0348 - val_accuracy: 0.9908\n",
170
+ "Epoch 8/15\n",
171
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0495 - accuracy: 0.9845 - val_loss: 0.0342 - val_accuracy: 0.9907\n",
172
+ "Epoch 9/15\n",
173
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0462 - accuracy: 0.9853 - val_loss: 0.0313 - val_accuracy: 0.9910\n",
174
+ "Epoch 10/15\n",
175
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0444 - accuracy: 0.9858 - val_loss: 0.0320 - val_accuracy: 0.9907\n",
176
+ "Epoch 11/15\n",
177
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0418 - accuracy: 0.9872 - val_loss: 0.0303 - val_accuracy: 0.9913\n",
178
+ "Epoch 12/15\n",
179
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0410 - accuracy: 0.9874 - val_loss: 0.0276 - val_accuracy: 0.9922\n",
180
+ "Epoch 13/15\n",
181
+ "422/422 [==============================] - 1s 3ms/step - loss: 0.0381 - accuracy: 0.9875 - val_loss: 0.0292 - val_accuracy: 0.9912\n",
182
+ "Epoch 14/15\n",
183
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0368 - accuracy: 0.9879 - val_loss: 0.0291 - val_accuracy: 0.9920\n",
184
+ "Epoch 15/15\n",
185
+ "422/422 [==============================] - 1s 2ms/step - loss: 0.0356 - accuracy: 0.9888 - val_loss: 0.0257 - val_accuracy: 0.9925\n"
186
+ ]
187
+ },
188
+ {
189
+ "data": {
190
+ "text/plain": [
191
+ "<keras.callbacks.History at 0x1c9d4871f40>"
192
+ ]
193
+ },
194
+ "execution_count": 5,
195
+ "metadata": {},
196
+ "output_type": "execute_result"
197
+ }
198
+ ],
199
+ "source": [
200
+ "batch_size = 128\n",
201
+ "epochs = 15\n",
202
+ "\n",
203
+ "model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
204
+ "\n",
205
+ "model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "metadata": {},
211
+ "source": [
212
+ "## Evaluate the Trained Model"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "execution_count": 6,
218
+ "metadata": {},
219
+ "outputs": [
220
+ {
221
+ "name": "stdout",
222
+ "output_type": "stream",
223
+ "text": [
224
+ "Test loss: 0.026043808087706566\n",
225
+ "Test accuracy: 0.9907000064849854\n"
226
+ ]
227
+ }
228
+ ],
229
+ "source": [
230
+ "score = model.evaluate(x_test, y_test, verbose=0)\n",
231
+ "print(\"Test loss:\", score[0])\n",
232
+ "print(\"Test accuracy:\", score[1])"
233
+ ]
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "execution_count": 7,
238
+ "metadata": {},
239
+ "outputs": [],
240
+ "source": [
241
+ "model.save(\"mnist.h5\")"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "markdown",
246
+ "metadata": {},
247
+ "source": [
248
+ "## Example GUI"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": 11,
254
+ "metadata": {},
255
+ "outputs": [
256
+ {
257
+ "name": "stdout",
258
+ "output_type": "stream",
259
+ "text": [
260
+ "4\n"
261
+ ]
262
+ }
263
+ ],
264
+ "source": [
265
+ "from tkinter import *\n",
266
+ "from PIL import ImageGrab\n",
267
+ "import imageio\n",
268
+ "import tkinter.font as font\n",
269
+ "\n",
270
+ "class Paint(object):\n",
271
+ " def __init__(self):\n",
272
+ " self.root=Tk()\n",
273
+ " self.root.title('Playing with numbers')\n",
274
+ " # self.root.wm_iconbitmap('44143.ico')\n",
275
+ " self.root.configure(background='light salmon')\n",
276
+ " self.c = Canvas(self.root,bg='light cyan', height=330, width=400)\n",
277
+ " self.label = Label(self.root, text='Draw any numer', font=20, bg='light salmon')\n",
278
+ " self.label.grid(row=0, column=3)\n",
279
+ " self.c.grid(row=1, columnspan=9)\n",
280
+ " self.c.create_line(0,0,400,0,width=20,fill='midnight blue')\n",
281
+ " self.c.create_line(0,0,0,330,width=20,fill='midnight blue')\n",
282
+ " self.c.create_line(400,0,400,330,width=20,fill='midnight blue')\n",
283
+ " self.c.create_line(0,330,400,330,width=20,fill='midnight blue')\n",
284
+ " self.myfont = font.Font(size=20,weight='bold')\n",
285
+ " 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",
286
+ " self.predicting_button.grid(row=2,column=1)\n",
287
+ " self.clear=Button(self.root,text='Clear', fg='white', bg='orange', height=2, width=6, font=self.myfont, command=self.clear)\n",
288
+ " self.clear.grid(row=2,column=5)\n",
289
+ " self.prediction_text = Text(self.root, height=5, width=5)\n",
290
+ " self.prediction_text.grid(row=4, column=3)\n",
291
+ " self.label=Label(self.root, text=\"Predicted Number is\", fg=\"black\", font=30, bg='light salmon')\n",
292
+ "\n",
293
+ " self.label.grid(row=3,column=3)\n",
294
+ " self.model=model\n",
295
+ " self.setup()\n",
296
+ " self.root.mainloop()\n",
297
+ "\n",
298
+ "\n",
299
+ " def setup(self):\n",
300
+ " self.old_x=None\n",
301
+ " self.old_y=None\n",
302
+ " self.color='black'\n",
303
+ " self.linewidth=15\n",
304
+ " self.c.bind('<B1-Motion>', self.paint)\n",
305
+ " self.c.bind('<ButtonRelease-1>', self.reset)\n",
306
+ "\n",
307
+ "\n",
308
+ " def paint(self,event):\n",
309
+ " paint_color=self.color\n",
310
+ " if self.old_x and self.old_y:\n",
311
+ " self.c.create_line(self.old_x,self.old_y,event.x,event.y,fill=paint_color,width=self.linewidth,capstyle=ROUND,\n",
312
+ " smooth=TRUE,splinesteps=48)\n",
313
+ " self.old_x=event.x\n",
314
+ " self.old_y=event.y\n",
315
+ "\n",
316
+ "\n",
317
+ " def clear(self):\n",
318
+ " \"\"\"Clear drawing area\"\"\"\n",
319
+ " self.c.delete(\"all\")\n",
320
+ "\n",
321
+ " def reset(self, event):\n",
322
+ " \"\"\"reset old_x and old_y if the left mouse button is released\"\"\"\n",
323
+ " self.old_x, self.old_y = None, None\n",
324
+ "\n",
325
+ "\n",
326
+ " def classify(self,widget):\n",
327
+ " x=self.root.winfo_rootx()+widget.winfo_x()\n",
328
+ " y=self.root.winfo_rooty()+widget.winfo_y()\n",
329
+ " x1=widget.winfo_width()\n",
330
+ " y1=widget.winfo_height()\n",
331
+ " ImageGrab.grab().crop((x,y,x1,y1)).resize((28,28)).save('classify.png')\n",
332
+ " img=imageio.imread('classify.png', as_gray=True, pilmode='P')\n",
333
+ " img=np.array(img)\n",
334
+ " img=np.reshape(img,(1,28,28,1))\n",
335
+ " img[img==0] = 255\n",
336
+ " img[img==225] = 0\n",
337
+ " # Predict digit\n",
338
+ " pred = self.model.predict([img])\n",
339
+ " # Get index with highest probability\n",
340
+ " pred = np.argmax(pred)\n",
341
+ " print(pred)\n",
342
+ " self.prediction_text.delete(\"1.0\", END)\n",
343
+ " self.prediction_text.insert(END, pred)\n",
344
+ " labelfont = ('times', 30, 'bold')\n",
345
+ " self.prediction_text.config(font=labelfont)\n",
346
+ "\n",
347
+ "if __name__ == '__main__':\n",
348
+ " Paint()"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": null,
354
+ "metadata": {},
355
+ "outputs": [],
356
+ "source": []
357
+ }
358
+ ],
359
+ "metadata": {
360
+ "kernelspec": {
361
+ "display_name": "Python 3.9.7 ('base')",
362
+ "language": "python",
363
+ "name": "python3"
364
+ },
365
+ "language_info": {
366
+ "codemirror_mode": {
367
+ "name": "ipython",
368
+ "version": 3
369
+ },
370
+ "file_extension": ".py",
371
+ "mimetype": "text/x-python",
372
+ "name": "python",
373
+ "nbconvert_exporter": "python",
374
+ "pygments_lexer": "ipython3",
375
+ "version": "3.9.7"
376
+ },
377
+ "orig_nbformat": 4,
378
+ "vscode": {
379
+ "interpreter": {
380
+ "hash": "ad2bdc8ecc057115af97d19610ffacc2b4e99fae6737bb82f5d7fb13d2f2c186"
381
+ }
382
+ }
383
+ },
384
+ "nbformat": 4,
385
+ "nbformat_minor": 2
386
+ }