if tensor is of variable type , no need to add watch
1 2 3 4 5
x = tf.Variable(2.0) with tf.GradientTape() as tape: y = x**2 + 2*x + 5 gradient = tape.gradient(y, x).numpy() print(gradient)
6.0
gradient tape can be used for multiple variable simultaneously
1 2 3 4 5 6 7 8 9 10 11 12
# (x, y) = (2.0, 5.0) # for x = 2, 2x + 2 = 2*2 + 2 = 6 # for y = 5, 2y + 2 = 5*2 + 2 = 12
x = tf.Variable(2.0) y = tf.Variable(5.0) with tf.GradientTape() as tape: eq_x = x**2 + 2*x + 5 eq_y = y**2 + 2*y + 5 greds = tape.gradient([eq_x, eq_y], [x, y]) for gred in greds: print('Gradient is:', gred.numpy())
Gradient is: 6.0
Gradient is: 12.0
higher order derivatives can also be computed with nested loops
1 2 3 4 5 6 7 8 9
x = tf.Variable(3.0) with tf.GradientTape() as g: with tf.GradientTape() as gg: y = x * x * x dy_dx = gg.gradient(y, x) d2y_dx2 = g.gradient(dy_dx, x)
print(dy_dx.numpy()) print(d2y_dx2.numpy())
27.0
18.0
we can set set the default watch condition to false , by that we can compute gradient for only the variables we want
Usage : in transfer learning
1 2 3 4 5 6
## code same as before , but nothing is computed this time x = tf.Variable(2.0) with tf.GradientTape(watch_accessed_variables=False) as tape: y = x**2 + 2*x + 5 gradient = tape.gradient(y, x) print(gradient)
None
gradient tapes are by default not presistent
the resources held by a GradientTape are released as soon as GradientTape.gradient() method is called
1 2 3 4 5 6 7 8 9
a = tf.Variable(6.0, trainable=True) b = tf.Variable(2.0, trainable=True) with tf.GradientTape() as tape: y1 = a * a * a y2 = b ** 3# will give error
108.0
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-19-dfc355cfc885> in <module>
6
7 print(tape.gradient(y1, a).numpy())
----> 8 print(tape.gradient(y2, b).numpy())
9
10
D:\Anaconda3\envs\tf_env\lib\site-packages\tensorflow_core\python\eager\backprop.py in gradient(self, target, sources, output_gradients, unconnected_gradients)
978 """
979 if self._tape is None:
--> 980 raise RuntimeError("GradientTape.gradient can only be called once on "
981 "non-persistent tapes.")
982 if self._recording:
RuntimeError: GradientTape.gradient can only be called once on non-persistent tapes.
1 2 3 4 5 6 7 8
a = tf.Variable(6.0) b = tf.Variable(2.0) with tf.GradientTape(persistent=True) as tape: y1 = a * a * a y2 = b ** 3
temporarily pauses the tapes recording, leading to greater computation speed
in long functions, it is more readable to use stop_recording blocks multiple times to calculate gradients in the middle of a function, than to calculate all the gradients at the end of a function
1 2 3 4 5 6
x = tf.Variable(3.0, trainable=True) with tf.GradientTape() as tape: y = x**3 with tape.stop_recording(): print(tape.gradient(y, x).numpy()) # -> 27.0
27.0
1 2 3 4 5 6 7 8 9 10 11
a = tf.Variable(6.0, trainable=True) b = tf.Variable(2.0, trainable=True) with tf.GradientTape(persistent=True) as tape: y1 = a ** 2 with tape.stop_recording(): print(tape.gradient(y1, a).numpy())
y2 = b ** 3 with tape.stop_recording(): print(tape.gradient(y2, b).numpy())
# Training data x_train = np.asarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y_train = np.asarray([i*10+5for i in x_train]) # y = 10x+5
# Loss function defloss(real_y, pred_y): return tf.abs(real_y - pred_y)
losses = []
# Trainable variables a = tf.Variable(random.random(), trainable=True) b = tf.Variable(random.random(), trainable=True)
# Step function defstep(real_x, real_y,e): with tf.GradientTape(persistent=True) as tape: # Make prediction pred_y = a * real_x + b # Calculate loss reg_loss = loss(real_y, pred_y) losses.append(tf.reduce_sum(reg_loss))
# Calculate gradients (for both of the variables) a_gradients, b_gradients = tape.gradient(reg_loss, [a, b])
# 2.2 - Classifying MNIST from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, MaxPooling2D from tensorflow.keras.models import Sequential from tensorflow.keras.initializers import RandomNormal from tensorflow.keras.datasets import mnist from tensorflow.keras.optimizers import Adam import matplotlib.pyplot as plt import random import math %matplotlib inline
# Step function defstep(real_x, real_y): with tf.GradientTape() as tape: # Make prediction pred_y = model(real_x.reshape((-1, 28, 28, 1))) # Calculate loss model_loss = tf.keras.losses.categorical_crossentropy(real_y, pred_y)
# Training loop bat_per_epoch = math.floor(len(x_train) / batch_size) for epoch inrange(epochs): print('=', end='') for i inrange(bat_per_epoch): n = i*batch_size step(x_train[n:n+batch_size], y_train[n:n+batch_size])
# Calculate accuracy model.compile(optimizer=optimizer, loss=tf.losses.categorical_crossentropy, metrics=['acc']) # Compile just for evaluation print('\nAccuracy:', model.evaluate(x_test, y_test, verbose=0)[1])
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 14s 1us/step
=WARNING:tensorflow:Layer conv2d 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.
========================
Accuracy: 0.9911