# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="4kyB8MUKn7Vh"
# # MNIST with Convolutional Neural Networks

# + [markdown] id="YyFM4icCoAaX"
# ## Prerequisites
#
# Install the following packages

# + colab={"base_uri": "https://localhost:8080/"} id="u63awVMPoD7Y" outputId="9d63b7c2-f9f5-46a5-816b-e9a8efaa6bed"
# ! pip3 install cloudmesh-installer
# ! pip3 install cloudmesh-common

# + [markdown] id="RlBJ-XuWopPh"
# ## Import Libraries

# + id="RylyDeO2oC4m"
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout
from keras.layers import Conv2D, MaxPooling2D, Flatten, AveragePooling2D
from keras.utils import to_categorical, plot_model
from keras.datasets import mnist

# + [markdown] id="e2lUNBJxore4"
# ## Download Data and Pre-Process

# + colab={"base_uri": "https://localhost:8080/"} id="3X9sLwfUocZ6" outputId="c7856a83-0d33-44c5-a71e-ee9364dad122"
(x_train, y_train), (x_test, y_test) = mnist.load_data()

num_labels = len(np.unique(y_train))

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

image_size = x_train.shape[1]
x_train = np.reshape(x_train,[-1, image_size, image_size, 1])
x_test = np.reshape(x_test,[-1, image_size, image_size, 1])
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

input_shape = (image_size, image_size, 1)
print(input_shape)
batch_size = 128
kernel_size = 3
pool_size = 2
filters = 64
dropout = 0.2

# + [markdown] id="O8DwuhcaowYQ"
# ## Define Model

# + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="O4tidxRFofEj" outputId="325d5686-f256-4620-f2f6-61c8e49e447c"
model = Sequential()
model.add(Conv2D(filters=filters,
                 kernel_size=kernel_size,
                 activation='relu',
                 input_shape=input_shape,
                 padding='same'))
model.add(MaxPooling2D(pool_size))
model.add(Conv2D(filters=filters,
                 kernel_size=kernel_size,
                 activation='relu',
                 input_shape=input_shape,
                 padding='same'))
model.add(MaxPooling2D(pool_size))
model.add(Conv2D(filters=filters,
                 kernel_size=kernel_size,
                 activation='relu',
                 padding='same'))
model.add(MaxPooling2D(pool_size))
model.add(Conv2D(filters=filters,
                 kernel_size=kernel_size,
                 activation='relu'))
model.add(Flatten())
model.add(Dropout(dropout))
model.add(Dense(num_labels))
model.add(Activation('softmax'))
model.summary()
plot_model(model, to_file='cnn-mnist.png', show_shapes=True)

# + [markdown] id="ZxW3sG8WoyYC"
# # Train

# + colab={"base_uri": "https://localhost:8080/"} id="SjT5wffFoiEg" outputId="ad0eba1c-cc81-481c-fcd8-45a89be382c2"
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# train the network
model.fit(x_train, y_train, epochs=10, batch_size=batch_size)

# + [markdown] id="E3jjqPJqoljt"
# ## Test

# + colab={"base_uri": "https://localhost:8080/"} id="2B1-bFcvokdd" outputId="c9703915-ae16-415a-ef16-5382747b6b3b"
loss, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
print("\nTest accuracy: %.1f%%" % (100.0 * acc))

StarcoderdataJupyterScriptsDedupFiltered