🧡💛💚TensorFlow2实战-系列教程 总目录
有任何问题欢迎在下面留言
本篇文章的代码运行界面均在Jupyter Notebook中进行
本篇文章配套的代码资源已经上传
Resnet实战1
Resnet实战2
Resnet实战3
7、训练脚本train.py解读------配置训练参数
# create modelmodel = get_model()# define loss and optimizerloss_object = tf.keras.losses.SparseCategoricalCrossentropy()optimizer = tf.keras.optimizers.Adam(lr=0.001)train_loss = tf.keras.metrics.Mean(name='train_loss')train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')valid_loss = tf.keras.metrics.Mean(name='valid_loss')valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='valid_accuracy')
- 前面已经解析了模型的构建
- loss_object,多元交叉熵损失函数
- optimizer ,Adam优化器,学习率为0.001
- train_loss ,返回的是batch的平均损失
- train_accuracy ,loss计算方法对应的准确率计算方法
- valid_loss 和valid_accuracy 是验证集的平均损失和准确率计算方法
8、训练脚本train.py解读------模型训练
@tf.function
def train_step(images, labels):with tf.GradientTape() as tape:predictions = model(images, training=True)loss = loss_object(y_true=labels, y_pred=predictions)gradients = tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(grads_and_vars=zip(gradients, model.trainable_variables))train_loss(loss)train_accuracy(labels, predictions)@tf.function
def valid_step(images, labels):predictions = model(images, training=False)v_loss = loss_object(labels, predictions)valid_loss(v_loss)valid_accuracy(labels, predictions)
train_step(images, labels)
函数:
- 装饰器
@tf.function
将这个函数转换为 TensorFlow 图,这可以提高执行效率。 with tf.GradientTape() as tape
:这是一个自动微分的上下文管理器,用于记录在其内部执行的所有操作,以便于后续计算梯度predictions = model(images, training=True)
:通过模型传递输入图像,得到预测结果。training=True
表示模型在训练模式下运行loss = loss_object(y_true=labels, y_pred=predictions)
:计算真实标签和预测标签之间的损失。gradients = tape.gradient(loss, model.trainable_variables)
:计算损失相对于模型可训练变量的梯度。optimizer.apply_gradients(grads_and_vars=zip(gradients, model.trainable_variables))
:应用梯度下降算法来更新模型的权重。train_loss(loss)
和train_accuracy(labels, predictions)
:更新训练损失和准确率的指标。
valid_step(images, labels)
函数,不需要计算梯度,其他都一样
for epoch in range(config.EPOCHS):train_loss.reset_states()train_accuracy.reset_states()valid_loss.reset_states()valid_accuracy.reset_states()step = 0for images, labels in train_dataset:step += 1train_step(images, labels)print("Epoch: {}/{}, step: {}/{}, loss: {:.5f}, accuracy: {:.5f}".format(epoch + 1, config.EPOCHS, step, math.ceil(train_count / config.BATCH_SIZE), train_loss.result(), train_accuracy.result()))for valid_images, valid_labels in valid_dataset:valid_step(valid_images, valid_labels)print("Epoch: {}/{}, train loss: {:.5f}, train accuracy: {:.5f}, ""valid loss: {:.5f}, valid accuracy: {:.5f}".format(epoch + 1, config.EPOCHS, train_loss.result(), train_accuracy.result(), valid_loss.result(), valid_accuracy.result()))model.save_weights(filepath=config.save_model_dir, save_format='tf')
- 逐个epoch执行训练
- 重置训练和验证的损失及准确率计算
- step 归0
- 训练集一个batch一个batch取数据
- step +1
- 调用train_step()函数训练当前batch数据
- 打印当前batch训练信息
- 验证集集一个batch一个batch取数据
- 调用valid_step()函数验证当前batch数据
- 在训练完成后,保存模型的权重
Resnet实战1
Resnet实战2
Resnet实战3