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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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q5DtHwQEzfyR"
      },
      "source": [
        "# Simple MNIST convnet\n",
        "\n",
        "**Author:** [fchollet](https://twitter.com/fchollet)<br>\n",
        "**Date created:** 2015/06/19<br>\n",
        "**Last modified:** 2020/04/21<br>\n",
        "**Description:** A simple convnet that achieves ~99% test accuracy on MNIST."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eZlWB3GpzfyT"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "8utAtD_ozfyU"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "from tensorflow import keras\n",
        "from tensorflow.keras import layers"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gbQiYBo1zfyV"
      },
      "source": [
        "## Prepare the data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "qJZ6R9iFzfyV",
        "outputId": "76eaada0-0f90-41e1-fa22-866d75351911",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n",
            "11493376/11490434 [==============================] - 0s 0us/step\n",
            "11501568/11490434 [==============================] - 0s 0us/step\n",
            "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",
        "# the data, split 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",
        "# 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": {
        "id": "kqdKUp6tzfyV"
      },
      "source": [
        "## Build the model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "GCmWGoyGzfyW",
        "outputId": "85fad2b6-4b43-406c-bab6-4097a0741b6d",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "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": {
        "id": "lhwcwv48zfyX"
      },
      "source": [
        "## Train the model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "lTElNbSEzfyX",
        "outputId": "22052ddf-9388-4916-84f8-eaecca77d186",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Epoch 1/10\n",
            "422/422 [==============================] - 46s 107ms/step - loss: 0.3677 - accuracy: 0.8880 - val_loss: 0.0825 - val_accuracy: 0.9780\n",
            "Epoch 2/10\n",
            "422/422 [==============================] - 45s 106ms/step - loss: 0.1108 - accuracy: 0.9664 - val_loss: 0.0628 - val_accuracy: 0.9837\n",
            "Epoch 3/10\n",
            "422/422 [==============================] - 45s 106ms/step - loss: 0.0860 - accuracy: 0.9732 - val_loss: 0.0453 - val_accuracy: 0.9877\n",
            "Epoch 4/10\n",
            "422/422 [==============================] - 44s 104ms/step - loss: 0.0703 - accuracy: 0.9786 - val_loss: 0.0435 - val_accuracy: 0.9875\n",
            "Epoch 5/10\n",
            "422/422 [==============================] - 44s 104ms/step - loss: 0.0599 - accuracy: 0.9810 - val_loss: 0.0398 - val_accuracy: 0.9890\n",
            "Epoch 6/10\n",
            "422/422 [==============================] - 44s 104ms/step - loss: 0.0556 - accuracy: 0.9830 - val_loss: 0.0364 - val_accuracy: 0.9898\n",
            "Epoch 7/10\n",
            "422/422 [==============================] - 45s 107ms/step - loss: 0.0509 - accuracy: 0.9838 - val_loss: 0.0333 - val_accuracy: 0.9910\n",
            "Epoch 8/10\n",
            "422/422 [==============================] - 46s 108ms/step - loss: 0.0477 - accuracy: 0.9847 - val_loss: 0.0314 - val_accuracy: 0.9920\n",
            "Epoch 9/10\n",
            "422/422 [==============================] - 44s 104ms/step - loss: 0.0443 - accuracy: 0.9859 - val_loss: 0.0319 - val_accuracy: 0.9930\n",
            "Epoch 10/10\n",
            "422/422 [==============================] - 43s 103ms/step - loss: 0.0409 - accuracy: 0.9869 - val_loss: 0.0299 - val_accuracy: 0.9923\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<keras.callbacks.History at 0x7fd82e27a850>"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ],
      "source": [
        "batch_size = 128\n",
        "epochs = 10\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": {
        "id": "YebG6y4izfyY"
      },
      "source": [
        "## Evaluate the trained model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "J5oNREXjzfyY",
        "outputId": "98337645-eefe-479c-9a2c-9c3cdbf41e2a",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Test loss: 0.027494722977280617\n",
            "Test accuracy: 0.9898999929428101\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",
      "source": [
        "!curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash"
      ],
      "metadata": {
        "id": "BOyNRT863adC",
        "outputId": "659ef954-5a83-49ea-926c-d9f367b38d2b",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Detected operating system as Ubuntu/bionic.\n",
            "Checking for curl...\n",
            "Detected curl...\n",
            "Checking for gpg...\n",
            "Detected gpg...\n",
            "Running apt-get update... done.\n",
            "Installing apt-transport-https... done.\n",
            "Installing /etc/apt/sources.list.d/github_git-lfs.list...done.\n",
            "Importing packagecloud gpg key... done.\n",
            "Running apt-get update... done.\n",
            "\n",
            "The repository is setup! You can now install packages.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install huggingface-hub\n",
        "!curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash\n",
        "!sudo apt-get install git-lfs\n",
        "!git-lfs install"
      ],
      "metadata": {
        "id": "rMkFpfhk0XOk",
        "outputId": "047a5b9f-c8bd-467d-84d2-a7b4960a26d9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Reading package lists... Done\n",
            "Building dependency tree       \n",
            "Reading state information... Done\n",
            "The following NEW packages will be installed:\n",
            "  git-lfs\n",
            "0 upgraded, 1 newly installed, 0 to remove and 40 not upgraded.\n",
            "Need to get 6,526 kB of archives.\n",
            "After this operation, 14.7 MB of additional disk space will be used.\n",
            "Get:1 https://packagecloud.io/github/git-lfs/ubuntu bionic/main amd64 git-lfs amd64 3.0.2 [6,526 kB]\n",
            "Fetched 6,526 kB in 1s (5,795 kB/s)\n",
            "debconf: unable to initialize frontend: Dialog\n",
            "debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 1.)\n",
            "debconf: falling back to frontend: Readline\n",
            "debconf: unable to initialize frontend: Readline\n",
            "debconf: (This frontend requires a controlling tty.)\n",
            "debconf: falling back to frontend: Teletype\n",
            "dpkg-preconfigure: unable to re-open stdin: \n",
            "Selecting previously unselected package git-lfs.\n",
            "(Reading database ... 155222 files and directories currently installed.)\n",
            "Preparing to unpack .../git-lfs_3.0.2_amd64.deb ...\n",
            "Unpacking git-lfs (3.0.2) ...\n",
            "Setting up git-lfs (3.0.2) ...\n",
            "Git LFS initialized.\n",
            "Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!huggingface-cli login"
      ],
      "metadata": {
        "id": "uZWWvPH82quN",
        "outputId": "f5c83a3b-62de-4ffd-db6a-25eed36bf9b0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "        _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|\n",
            "        _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|\n",
            "        _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|\n",
            "        _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|\n",
            "        _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|\n",
            "\n",
            "        To login, `huggingface_hub` now requires a token generated from https://huggingface.co/settings/token.\n",
            "        (Deprecated, will be removed in v0.3.0) To login with username and password instead, interrupt with Ctrl+C.\n",
            "        \n",
            "Token: \n",
            "Login successful\n",
            "Your token has been saved to /root/.huggingface/token\n",
            "\u001b[1m\u001b[31mAuthenticated through git-credential store but this isn't the helper defined on your machine.\n",
            "You might have to re-authenticate when pushing to the Hugging Face Hub. Run the following command in your terminal in case you want to set this credential helper as the default\n",
            "\n",
            "git config --global credential.helper store\u001b[0m\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub.keras_mixin import push_to_hub_keras\n",
        "push_to_hub_keras(model = model, repo_url = \"https://huggingface.co/keras-io/simple-mnist-convnet\", organization = \"keras-io\")"
      ],
      "metadata": {
        "id": "RhssM1Dy0sl_"
      },
      "execution_count": 11,
      "outputs": []
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "mnist_convnet",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.7.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}