<jupyter_start><jupyter_text><jupyter_code>!pip install coremltools
google_drive_proj_dir = '/content/drive/MyDrive/Vienna University of Technology/mnist-sample'
import coremltools as ct
import matplotlib.cm as cm
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import os
import tensorflow as tf

from PIL import Image
from tensorflow.keras import backend as K
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, Input, MaxPooling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
print(X_train.shape)
print(Y_train.shape)

print(X_test.shape)
print(Y_test.shape)
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_train = X_train.astype('float32')/255
Y_train = to_categorical(Y_train, 10)

X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_test = X_test.astype('float32')/255
Y_test = to_categorical(Y_test, 10)
fig = plt.figure(figsize=(20, 20))
for i in range(6):
    ax = fig.add_subplot(1, 6, i+1, 
                         xticks=[], 
                         yticks=[])
    ax.imshow(np.squeeze(X_train[i], axis=-1), cmap='gray')
    ax.set_title(str(Y_train[i]))
model = Sequential()

model.add(Input(shape=(28, 28, 1)))
model.add(Conv2D(filters=32, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
# model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', 
              optimizer=Adam(), 
              metrics=['accuracy'])

model.fit(X_train, Y_train, batch_size=512, epochs=16, verbose=1)

score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Define the input type as image
image_input = ct.ImageType(shape=(1, 28, 28, 1), scale=1/255)

# set class labels
classifier_config = ct.ClassifierConfig(
    class_labels=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])

# Convert the model using the Unified Conversion API
model = ct.convert(
    model, inputs=[image_input], classifier_config=classifier_config)
# Save model
model.save(os.path.join(google_drive_proj_dir, 'MNISTSample.mlmodel'))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1495916852264291, 'fraction_numerical': 0.03749072011878248, 'mean_word_length': 5.720698254364089, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '466261', 'license': 'MIT', 'n_tokens_mistral': 1060, 'n_tokens_neox': 992, 'n_words': 206, 'path': 'main.ipynb', 'repo_name': 'srasoulzadeh/tensorflow-keras-coreml-mnist-sample', 'size': '2694'}