Tensorflow for advanced
    • PDF

    Tensorflow for advanced

    • PDF

    Article Summary

    Available in Classic and VPC

    For more examples and details, please refer to TensorFlow tutorial.

    Import TensorFlow library to the program first:

    import tensorflow as tf
    
    from tensorflow.keras.layers import Dense, Flatten, Conv2D
    from tensorflow.keras import Model
    

    Load MNIST dataset and prepare it.

    mnist = tf.keras.datasets.mnist
    
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x_train, x_test = x_train / 255.0, x_test / 255.0
    
    # Add channel dimensions.
    x_train = x_train[..., tf.newaxis]
    x_test = x_test[..., tf.newaxis]
    

    Use f.data to shuffle the dataset and create batches:

    train_ds = tf.data.Dataset.from_tensor_slices(
        (x_train, y_train)).shuffle(10000).batch(32)
    test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
    

    Use Model subclassing API of Keras to create the tf.keras model:

    class MyModel(Model):
      def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = Conv2D(32, 3, activation='relu')
        self.flatten = Flatten()
        self.d1 = Dense(128, activation='relu')
        self.d2 = Dense(10, activation='softmax')
    
      def call(self, x):
        x = self.conv1(x)
        x = self.flatten(x)
        x = self.d1(x)
        return self.d2(x)
    
    model = MyModel()
    

    Select the optimizer and loss function required for training:

    loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
    
    optimizer = tf.keras.optimizers.Adam()
    

    Select indicators to measure the model's loss and performance. Print the final result based on the measuring indicators collected while the epoch is running.

    train_loss = tf.keras.metrics.Mean(name='train_loss')
    train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
    
    test_loss = tf.keras.metrics.Mean(name='test_loss')
    test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
    

    Use tf.GradientTape to train the model:

    @tf.function
    def train_step(images, labels):
      with tf.GradientTape() as tape:
        predictions = model(images)
        loss = loss_object(labels, predictions)
      gradients = tape.gradient(loss, model.trainable_variables)
      optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    
      train_loss(loss)
      train_accuracy(labels, predictions)
    

    Now, test the model:

    @tf.function
    def test_step(images, labels):
      predictions = model(images)
      t_loss = loss_object(labels, predictions)
    
      test_loss(t_loss)
      test_accuracy(labels, predictions)
    
    EPOCHS = 5
    
    for epoch in range(EPOCHS):
      for images, labels in train_ds:
        train_step(images, labels)
    
      for test_images, test_labels in test_ds:
        test_step(test_images, test_labels)
    
      template = "epoch: {}, loss: {}, accuracy: {}, test loss: {}, test accuracy: {}"
      print (template.format(epoch+1,
                             train_loss.result(),
                             train_accuracy.result()*100,
                             test_loss.result(),
                             test_accuracy.result()*100))
                             
    '''
    WARNING:tensorflow:Entity <function train_step at 0x7f24a41c2b70> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Str'
    WARNING: Entity <function train_step at 0x7f24a41c2b70> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Str'
    WARNING:tensorflow:Layer my_model is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2.  The layer has dtype float32 because it's dtype defaults to floatx.
    
    If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.
    
    To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.
    
    WARNING:tensorflow:Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING: Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING:tensorflow:Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7f24a13f4840> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'
    WARNING: Entity <function Function._initialize_uninitialized_variables.<locals>.initialize_variables at 0x7f24a13f4840> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Num'
    WARNING:tensorflow:Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING: Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING:tensorflow:Entity <function test_step at 0x7f24a41c2bf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Str'
    WARNING: Entity <function test_step at 0x7f24a41c2bf8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: module 'gast' has no attribute 'Str'
    WARNING:tensorflow:Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING: Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING:tensorflow:Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    WARNING: Entity <bound method MyModel.call of <__main__.MyModel object at 0x7f24a14b7908>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4
    Epoch: 1, loss: 0.1347680389881134, accuracy: 95.9366683959961, test loss: 0.05350242182612419, test accuracy: 98.12999725341797
    Epoch: 2, loss: 0.0896165519952774, accuracy: 97.27583312988281, test loss: 0.054728906601667404, test accuracy: 98.13500213623047
    Epoch: 3, loss: 0.06729747354984283, accuracy: 97.9477767944336, test loss: 0.05539105087518692, test accuracy: 98.16667175292969
    Epoch: 4, loss: 0.05394642427563667, accuracy: 98.34916687011719, test loss: 0.055290184915065765, test accuracy: 98.23750305175781
    Epoch: 5, loss: 0.04513656720519066, accuracy: 98.60933685302734, test loss: 0.05616115406155586, test accuracy: 98.27400207519531
    '''
    

    A trained image classifier achieves approximately 98% accuracy in this dataset. For more information, please refer to TensorFlow tutorial.


    Was this article helpful?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.