File size: 9,440 Bytes
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4789c9d
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4789c9d
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4789c9d
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4789c9d
 
 
 
 
 
 
 
 
 
 
 
e82c862
 
 
 
 
 
 
 
 
 
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
4789c9d
e82c862
 
 
 
 
4789c9d
e82c862
 
 
 
 
 
 
 
4789c9d
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4789c9d
 
e82c862
 
 
 
 
 
 
 
 
 
 
 
 
89e16b4
e82c862
 
 
 
89e16b4
e82c862
89e16b4
e82c862
89e16b4
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
{
 "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": 1,
   "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": 2,
   "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": 3,
   "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": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "epochs = 15\n",
    "\n",
    "model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/15\n",
      "422/422 [==============================] - 4s 3ms/step - loss: 0.3724 - accuracy: 0.8837 - val_loss: 0.0810 - val_accuracy: 0.9785\n",
      "Epoch 2/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.1118 - accuracy: 0.9671 - val_loss: 0.0562 - val_accuracy: 0.9852\n",
      "Epoch 3/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0835 - accuracy: 0.9739 - val_loss: 0.0481 - val_accuracy: 0.9872\n",
      "Epoch 4/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0700 - accuracy: 0.9787 - val_loss: 0.0404 - val_accuracy: 0.9898\n",
      "Epoch 5/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0604 - accuracy: 0.9815 - val_loss: 0.0381 - val_accuracy: 0.9910\n",
      "Epoch 6/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0559 - accuracy: 0.9826 - val_loss: 0.0354 - val_accuracy: 0.9903\n",
      "Epoch 7/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0505 - accuracy: 0.9829 - val_loss: 0.0338 - val_accuracy: 0.9903\n",
      "Epoch 8/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0484 - accuracy: 0.9847 - val_loss: 0.0296 - val_accuracy: 0.9923\n",
      "Epoch 9/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0443 - accuracy: 0.9860 - val_loss: 0.0333 - val_accuracy: 0.9912\n",
      "Epoch 10/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0422 - accuracy: 0.9869 - val_loss: 0.0308 - val_accuracy: 0.9927\n",
      "Epoch 11/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0397 - accuracy: 0.9874 - val_loss: 0.0321 - val_accuracy: 0.9922\n",
      "Epoch 12/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0375 - accuracy: 0.9875 - val_loss: 0.0269 - val_accuracy: 0.9928\n",
      "Epoch 13/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0355 - accuracy: 0.9886 - val_loss: 0.0296 - val_accuracy: 0.9925\n",
      "Epoch 14/15\n",
      "422/422 [==============================] - 1s 2ms/step - loss: 0.0340 - accuracy: 0.9888 - val_loss: 0.0291 - val_accuracy: 0.9928\n",
      "Epoch 15/15\n",
      "422/422 [==============================] - 1s 3ms/step - loss: 0.0321 - accuracy: 0.9894 - val_loss: 0.0277 - val_accuracy: 0.9927\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x14a08dfc3d0>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# This line can be run multiple times, but keep in mind that the model will probably be over fitting\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.02324853651225567\n",
      "Test accuracy: 0.9922000169754028\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": "markdown",
   "metadata": {},
   "source": [
    "## Save Model (h5 format)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save(\"mnist.h5\")"
   ]
  }
 ],
 "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
}