C1W3 Assignment
C1W3 Assignment
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
1
this case it is stored somewhere else, as a result of this, you need to specify the full path.
• load_data returns the train and test sets in the form of the tuples (x_train, y_train),
(x_test, y_test) but in this exercise you will be needing only the train set so you can
ignore the second tuple.
[3]: # grader-required-cell
def reshape_and_normalize(images):
2
# Normalize pixel values
images = images/255.0
return images
# Reload the images in case you run this cell multiple times
(training_images, _), _ = tf.keras.datasets.mnist.load_data(path=data_path)
[12]: # grader-required-cell
3
# Remember to inherit from the correct class
class myCallback(tf.keras.callbacks.Callback):
# Define the method that checks the accuracy at the end of each epoch
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy') >= .995):
print("\nReached 99.5% accuracy so cancelling training!")
self.model.stop_training = True
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax'),
])
### END CODE HERE
return model
4
[18]: # grader-required-cell
Epoch 1/10
1875/1875 [==============================] - 30s 16ms/step - loss: 0.1604 -
accuracy: 0.9542
Epoch 2/10
1875/1875 [==============================] - 30s 16ms/step - loss: 0.0560 -
accuracy: 0.9832
Epoch 3/10
1875/1875 [==============================] - 30s 16ms/step - loss: 0.0377 -
accuracy: 0.9880
Epoch 4/10
1875/1875 [==============================] - 30s 16ms/step - loss: 0.0274 -
accuracy: 0.9916
Epoch 5/10
1875/1875 [==============================] - 30s 16ms/step - loss: 0.0195 -
accuracy: 0.9940
Epoch 6/10
1869/1875 [============================>.] - ETA: 0s - loss: 0.0148 - accuracy:
0.9952 ETA: 1s
Reached 99.5% accuracy so cancelling training!
1875/1875 [==============================] - 30s 16ms/step - loss: 0.0148 -
accuracy: 0.9952
If you see the message that you defined in your callback printed out after less than 10 epochs it
means your callback worked as expected. You can also double check by running the following cell:
5
[19]: # grader-required-cell
import base64
encoded_answer =␣
,→"CiAgIC0gQSBDb252MkQgbGF5ZXIgd2l0aCAzMiBmaWx0ZXJzLCBhIGtlcm5lbF9zaXplIG9mIDN4MywgUmVMVSBhY3R
encoded_answer = encoded_answer.encode('ascii')
answer = base64.b64decode(encoded_answer)
answer = answer.decode('ascii')
print(answer)
6
“false” if you want to lock it
</li>
<li> On the notebook’s menu, click “View” > “Cell Toolbar” > “None” </li>
</ol>
<p> Here's a short demo of how to do the steps above:
<br>
<img src="https://drive.google.com/uc?export=view&id=14Xy_Mb17CZVgzVAgq7NCjMVBvSae3xO1" ali