调整权值w

 1 import tensorflow as tf
 2 import numpy as np
 3 w = tf.Variable(5, dtype=tf.float32)#定义权值w
 4 lr = 0.2                             #学习率
 5 epoch = 40
 6 
 7 for epoch in range(epoch):          # for epoch 定义顶层循环,表示对数据集循环epoch次,此例数据集数据仅有1个w,初始化时候constant赋值为5,循环40次迭代。
 8     with tf.GradientTape() as tape:  # with结构到grads框起了梯度的计算过程。
 9 
10         loss = tf.square(w + 1)       #计算损失率
11     grads = tape.gradient(loss, w)  # .gradient函数告知谁对谁求导
12     w.assign_sub(lr * grads)  # .assign_sub 对变量做自减 即:w -= lr*grads 即 w = w - lr*grads
13     print("After %s epoch,w is %f,loss is %f" % (epoch, w.numpy(), loss))