Skip to content

Instantly share code, notes, and snippets.

@satr
Created May 15, 2019 13:52
Show Gist options
  • Save satr/1a2cb1ac5d75c0aec03e53240730c299 to your computer and use it in GitHub Desktop.
Save satr/1a2cb1ac5d75c0aec03e53240730c299 to your computer and use it in GitHub Desktop.
Usage of TensorFlow callbacks
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
mnist = keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
#plt.imshow(test_images[0])
class FitCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
accuracy = 0.9
if logs.get('acc') > accuracy:
print("\nReached {:f}% accuracy - cancelling training.".format(accuracy * 100.0))
self.model.stop_training = True
callbacks = FitCallback()
training_images = training_images / 255.0
test_images = test_images / 255.0
model = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)), #images 28x28
tf.keras.layers.Dense(512, activation=tf.nn.relu), #512 neurones
tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) #10 classes
model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
#model.fit(training_images, training_labels, epochs=5) #instad of specifying amount of epochs - use callbacks with accuracy level
model.fit(training_images, training_labels, callbacks=[callbacks])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment