# 1. importimport tensorflow as tf
# 2. train and test
w = tf.Variable(tf.constant(5, dtype=tf.float32))# 3. model.sequential# 4. model.compile and 5. model.fit
lr =0.2
epochs =40for epoch inrange(epochs):with tf.GradientTape()as tape:
loss = tf.square(w +1)# 定义loss函数
grads = tape.gradient(loss, w)# 求loss对w的梯度
w.assign_sub(lr * grads)print("After %s epoch, w is %f, loss is %f"%(epoch, w.numpy(), loss))# 6. model.summary()