<jupyter_start><jupyter_text>http://preview.d2l.ai/d2l-en/master/chapter_preliminaries/autograd.html<jupyter_code>import tensorflow as tf
x = tf.range(4, dtype=tf.float32)
x
x = tf.Variable(x)
# Record all computations onto a tape
with tf.GradientTape() as t:
    y = 2 * tf.tensordot(x, x, axes=1)
y
x_grad = t.gradient(y, x)
x_grad
x_grad == 4 * x
with tf.GradientTape() as t:
    y = tf.reduce_sum(x)
t.gradient(y, x)  # Overwritten by the newly calculated gradient
with tf.GradientTape() as t:
    y = x * x
t.gradient(y, x)  # Same as `y = tf.reduce_sum(x * x)`
# Set `persistent=True` to run `t.gradient` more than once
with tf.GradientTape(persistent=True) as t:
    y = x * x
    u = tf.stop_gradient(y)
    z = u * x

x_grad = t.gradient(z, x)
x_grad == u
t.gradient(y, x) == 2 * x
def f(a):
    b = a * 2
    while tf.norm(b) < 1000:
        b = b * 2
    if tf.reduce_sum(b) > 0:
        c = b
    else:
        c = 100 * b
    return c
a = tf.Variable(tf.random.normal(shape=()))
with tf.GradientTape() as t:
    d = f(a)
d_grad = t.gradient(d, a)
d_grad
d_grad == d / a<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14838129496402877, 'fraction_numerical': 0.0170863309352518, 'mean_word_length': 3.032608695652174, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '311574', 'license': 'MIT', 'n_tokens_mistral': 501, 'n_tokens_neox': 470, 'n_words': 127, 'path': 'Ch02_Preliminaries/2-5tf.ipynb', 'repo_name': 'StevenJokess/d2l-en-read', 'size': '1112'}