{"cells":[{"metadata":{},"cell_type":"markdown","source":"You learned how to do classificaiton using Fashion MNIST, a data set containing items of clothing. There's another, similar dataset called MNIST which has items of handwriting -- the digits 0 through 9.\n\nWrite 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.\n\nSome notes:\n1. It should succeed in less than 10 epochs, so it is okay to change epochs= to 10, but nothing larger\n2. When it reaches 99% or greater it should print out the string \"Reached 99% accuracy so cancelling training!\"\n3. If you add any additional variables, make sure you use the same names as the ones used in the class\n\nI've started the code for you below -- how would you finish it? ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom os import path, getcwd, chdir\n\n# DO NOT CHANGE THE LINE BELOW. If you are developing in a local\n# environment, then grab mnist.npz from the Coursera Jupyter Notebook\n# and place it inside a local folder and edit the path to that location\npath = f\"{getcwd()}/../tmp2/mnist.npz\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def train_mnist():\n    \n    class myCallback(tf.keras.callbacks.Callback):\n        def on_epoch_end(self, epochs, logs = {}):\n            if(logs.get('acc')>0.99):\n                print(\"Reached 99% accuracy so cancelling training!\")\n                self.model.stop_training = True\n                \n    callbacks = myCallback()\n\n    mnist = tf.keras.datasets.mnist\n\n    (x_train, y_train),(x_test, y_test) = mnist.load_data(path=path)\n    \n    x_train = x_train / 255.0\n    x_test = x_test / 255.0\n    \n    model = tf.keras.models.Sequential([\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(512, activation = 'relu'),\n        tf.keras.layers.Dense(10, activation = 'softmax')\n        ])\n\n    model.compile(optimizer='adam',\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['accuracy'])\n   \n    history = model.fit(x_train, y_train, epochs = 5, callbacks = [callbacks])\n   \n    return history.epoch, history.history['acc'][-1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_mnist()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Another Way:","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nclass myCallback(tf.keras.callbacks.Callback):\n  def on_epoch_end(self, epoch, logs={}):\n    if(logs.get('accuracy')>0.6):\n      print(\"\\nReached 60% accuracy so cancelling training!\")\n      self.model.stop_training = True\n\nmnist = tf.keras.datasets.fashion_mnist\n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\ncallbacks = myCallback()\n\nmodel = tf.keras.models.Sequential([\n  tf.keras.layers.Flatten(input_shape=(28, 28)),\n  tf.keras.layers.Dense(512, activation=tf.nn.relu),\n  tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\nmodel.compile(optimizer=tf.optimizers.Adam(),\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=10, callbacks=[callbacks])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}