TF构造八股文
- Import: 导入相关的包
- train and test: 处理好训练与测试数据集,包括乱序等操作
- models.Sequential: 搭建网络模型
- model.compile: 设置优化算法,配置训练方法
- model.fit: 设置训练时的学习率,迭代次数,batch_size,对模型进行训练;
- model.summary:打印出网络结构和参数统计
简单实现
# 1. import
import 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 = 40
for epoch in range(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()