# ---
# 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
# ---

# + colab={"base_uri": "https://localhost:8080/"} id="VW-pW9ol3YLD" executionInfo={"status": "ok", "timestamp": 1623942006117, "user_tz": -540, "elapsed": 2056, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="66d06b17-8a1d-47c8-f0cf-d7e7c0ddd0a8"
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
import math

print(tf.__version__)


# + id="Q3KXrOKud7pZ" executionInfo={"status": "ok", "timestamp": 1623942006118, "user_tz": -540, "elapsed": 7, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}}
# Helper function to display digit images
def show_sample(images, labels, sample_count=25):
  # Create a square with can fit {sample_count} images
  grid_count = math.ceil(math.ceil(math.sqrt(sample_count)))
  grid_count = min(grid_count, len(images), len(labels))
  
  plt.figure(figsize=(2*grid_count, 2*grid_count))
  for i in range(sample_count):
    plt.subplot(grid_count, grid_count, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(images[i], cmap=plt.cm.gray)
    plt.xlabel(labels[i])
  plt.show()


# + colab={"base_uri": "https://localhost:8080/"} id="pE5LG4mi3k1R" executionInfo={"status": "ok", "timestamp": 1623942006484, "user_tz": -540, "elapsed": 372, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="f2473ecf-1dad-4572-ddc0-67f4297c126f"
# Download MNIST dataset.
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

a=len(train_images)
b=len(test_images)
print("학습 이미지 총수 = {}".format(a))
print("테스트 이미지 총수 = {}".format(b))

# + colab={"base_uri": "https://localhost:8080/", "height": 589} id="ZAqNS_BN3q4Y" executionInfo={"status": "ok", "timestamp": 1623942007735, "user_tz": -540, "elapsed": 1252, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="e625916a-4b6c-45e4-aac9-fdb6e1543c2a"
# Show the first 25 images in the training dataset.
show_sample(train_images, 
            ['Label: %s' % label for label in train_labels])

# + id="8cOb3Jjz4N1S" executionInfo={"status": "ok", "timestamp": 1623942007736, "user_tz": -540, "elapsed": 6, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}}
# Define the model architecture
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation=tf.nn.relu),

# Optional: You can replace the dense layer above with the convolution layers below to get higher accuracy.
    # keras.layers.Reshape(target_shape=(28, 28, 1)),
    # keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=tf.nn.relu),
    # keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=tf.nn.relu),
    # keras.layers.MaxPooling2D(pool_size=(2, 2)),
    # keras.layers.Dropout(0.25),
    # keras.layers.Flatten(input_shape=(28, 28)),
    # keras.layers.Dense(128, activation=tf.nn.relu),
    # keras.layers.Dropout(0.5),

    keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# + colab={"base_uri": "https://localhost:8080/"} id="UMWFfvF54Znv" executionInfo={"status": "ok", "timestamp": 1623942028563, "user_tz": -540, "elapsed": 20831, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="2254676e-7402-4c6c-ff1d-6db3123456cb"
# Train the digit classification model
model.fit(train_images, train_labels, epochs=5)

# + colab={"base_uri": "https://localhost:8080/"} id="erXJa4qN4T0a" executionInfo={"status": "ok", "timestamp": 1623942028564, "user_tz": -540, "elapsed": 7, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="15254b05-5d73-4f5f-da20-e2b9db76794c"
model.summary()

# + id="y1L9g1_87Ml_" colab={"base_uri": "https://localhost:8080/", "height": 589} executionInfo={"status": "ok", "timestamp": 1623942030908, "user_tz": -540, "elapsed": 1612, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="80ca70b1-8c79-4fea-ee35-c2ca06e8ddb3"
# Evaluate the model using test dataset.
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:{0} ===> {1}%'.format(test_acc, round(test_acc*100)))

# Predict the labels of digit images in our test dataset.
predictions = model.predict(test_images)

# Then plot the first 25 test images and their predicted labels.
show_sample(test_images, 
            ['Predicted: %d' % np.argmax(result) for result in predictions])

# + colab={"base_uri": "https://localhost:8080/"} id="GOeDWz-S48bR" executionInfo={"status": "ok", "timestamp": 1623942031534, "user_tz": -540, "elapsed": 629, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="a89e0c24-dc65-4330-d34a-81719b86a2ad"
# Save the model.
model_path = 'saved_model/mnist_model'
model.save(model_path)
print("DigitalCalssifier가 SavedModel로 저장되었습니다.")

# + colab={"base_uri": "https://localhost:8080/"} id="y1QgfTTk8Jir" executionInfo={"status": "ok", "timestamp": 1623942031920, "user_tz": -540, "elapsed": 389, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="72a37b6b-1327-4fbf-a3bd-bda76f027829"
# Convert Keras model to TF Lite format.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

# + id="ofpx5qNG8QPk" executionInfo={"status": "ok", "timestamp": 1623942031921, "user_tz": -540, "elapsed": 6, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}}
# Save the TF Lite model as file
f = open('mnist.tflite', "wb")
f.write(tflite_model)
f.close()

# + colab={"base_uri": "https://localhost:8080/", "height": 326} id="-IKS85hoez1U" executionInfo={"status": "ok", "timestamp": 1623942032320, "user_tz": -540, "elapsed": 404, "user": {"displayName": "\ud64d\uc11d\uc870", "photoUrl": "", "userId": "10469079239084506032"}} outputId="8534a5ef-16d4-406d-9dc8-f2763824477b"
###################### Verifying the '.tflite' file #######################

# CAUTION ###################################################
# However, this model is FAILED. This code doesn't work well.
# There is an only output result = 8
# The .tflite file only can read every digit as 8
#############################################################

# Download a test image
zero_img_path = keras.utils.get_file(
    'zero.png', 
    'https://storage.googleapis.com/khanhlvg-public.appspot.com/digit-classifier/zero.png'
    )

image = keras.preprocessing.image.load_img(
    zero_img_path,
    color_mode = 'grayscale',
    target_size=(28, 28),
    interpolation='bilinear'
    )

# Pre-process the image: Adding batch dimension and normalize the pixel value to [0..1]
# In training, we feed images in a batch to the model to improve training speed, making the model input shape to be (BATCH_SIZE, 28, 28).
# For inference, we still need to match the input shape with training, so we expand the input dimensions to (1, 28, 28) using np.expand_dims
input_image = np.expand_dims(np.array(image, dtype=np.float32) / 255.0, 0)

# Show the pre-processed input image
show_sample(input_image, ['Input Image'], 1)

# Read lite model for tensorflow
# tflite_model = None
tflite_path= "mnist.tflite"
with open(tflite_path, 'rb') as f:
  tflite_model= f.read()

# Run inference with TensorFlow Lite
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
interpreter.set_tensor(interpreter.get_input_details()[0]["index"], input_image)
interpreter.invoke()
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()[0] 

# Print the model's classification result
digit = np.argmax(output)

show_sample(input_image, ['Output={}'.format(digit)], 1)
print('Predicted Digit: {0}\nConfidence: {1} ===> {2}%'.format(digit, output[digit], round(output[digit]*100)))

StarcoderdataJupyterScriptsDedupFiltered