import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import tensorflow as tf tf.get_logger().setLevel("ERROR") x = tf.constant(3.0) with tf.GradientTape() as tape: tape.watch(x) y = x * x + 2.0 * x dy_dx = tape.gradient(y, x) weight = tf.Variable(2.0, name="weight") feature = tf.constant(3.0) target = tf.constant(15.0) optimizer = tf.keras.optimizers.SGD(learning_rate=0.05) weight_before = float(weight.numpy()) with tf.GradientTape() as tape: prediction = weight * feature loss = tf.square(prediction - target) gradients = tape.gradient(loss, [weight]) loss_before = float(loss.numpy()) optimizer.apply_gradients(zip(gradients, [weight])) prediction_after = weight * feature loss_after = tf.square(prediction_after - target) print(f"TensorFlow {tf.__version__}") print(f"dy/dx at x=3.0: {float(dy_dx.numpy()):.2f}") print(f"weight before: {weight_before:.2f}") print(f"loss before: {loss_before:.2f}") print(f"gradient for weight: {float(gradients[0].numpy()):.2f}") print(f"weight after: {float(weight.numpy()):.2f}") print(f"loss after: {float(loss_after.numpy()):.2f}") print(f"gradient connected: {gradients[0] is not None}")