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

# There's another, similar dataset called MNIST which has items of handwriting -- the digits 0 through 9.
#
# Write an MNIST classifier that trains to 99% accuracy or above, and does it without a fixed number of epochs -- i.e. you should stop training once you reach that level of accuracy.
#
# Some notes:
#
# It should succeed in less than 10 epochs, so it is okay to change epochs= to 10, but nothing larger
# When it reaches 99% or greater it should print out the string "Reached 99% accuracy so cancelling training!"
# If you add any additional variables, make sure you use the same names as the ones used in the class

# +
import tensorflow as tf
from os import path, getcwd, chdir

path = f"{getcwd()}/../tmp2/mnist.npz"


# -

def train_mnist():
    # please do not remove # model fitting inline comments.
    
    class myCallback(tf.keras.callbacks.Callback):
        def on_epoch_end(self, epochs, logs = {}):
            if(logs.get('acc')>0.99):
                print("Reached 99% accuracy so cancelling training!")
                self.model.stop_training = True
    
    callbacks = myCallback()

    mnist = tf.keras.datasets.mnist
    
    # Path to your local dataset here
    (x_train, y_train),(x_test, y_test) = mnist.load_data(path=path)
    
    x_train = x_train / 255.0
    x_test = x_test / 255.0

    model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(512, activation = 'relu'),
        tf.keras.layers.Dense(10, activation = 'softmax')
    ])

    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    # model fitting
    history = model.fit(
        x_train, y_train, epochs = 5, callbacks = [callbacks]
    )
    # model fitting
    return history.epoch, history.history['acc'][-1]


train_mnist()

StarcoderdataJupyterScriptsDedupFiltered