Keras回调函数Callbacks

       回调函数是一组在训练的特定阶段被调用的函数集,可以使用回调函数来观察训练过程中网络内部的状态和统计信息。通过传递回调函数列表到模型的.fit()中,即可在给定的训练阶段调用该函数集中的函数。

 

EarlyStopping

        keras.callbacks.EarlyStopping(monitor='val_loss', patience=0, verbose=0, mode='auto') 当监测值不再改善时,该回调函数将中止训练。

参数

1)Monitor:需要监视的量。

2)Min_delta:这个值用来定义什么是一个improvement,若上下间隔epoch之间值的绝对变化小于这个min_delta值,视为没有improvement。

3)Patience:能容忍多少次连续训练epochs,值没有improvement。

4)Mode:该参数是{“auto”,”min”,”max”}的其中之一;在min模式下当检测值不再下降patience次停止;在max模式下当检测值不再上升patience次停止;在auto模式下,上升还是下降取决于检测值的名字。

 

 

ModelCheckpoint

       该回调函数将在每个epoch后保存模型到filepath。

1)filepath: 可以是格式化的字符串,里面的占位符将会被epoch值和传入on_epoch_end的logs关键字所填入,例如filepath若为weights.{epoch:03d}-{val_loss:.3f}.h5,对对应生成epoch和验证集loss的多个文件。

2)save_best_only: 当设置为True时,只保存在验证集上性能最好的模型。

3)save_weights_only: 若设置为True,则只保存模型权重,否则将保存整个模型(包括模型结构和配置信息)

 

 

Tensorbord

一、tensorboard简介

       机器学习涉及到理解一些重要的度量指标例如损失函数以及它们如何随着训练的变化而变化。特别是在训练模型发生过拟合时这些指标可帮助你更容易理解到:模型不需要训练太长的时间。tensorboard提供了可视化界面及为机器学习过程中提供所需工具。

     1)跟踪并可视化像损失(loss)和精度(accuracy)这样的矩阵。

     2)可视化模型图(包括ops和layer)

     3)随着时间变化而变化的权重(weights)、偏置(biases)及其他tensor的直方图可视化

     。。。

 

二、tensorboard例程

1、简单例程(tensorboard的使用)

      以下是两个矩阵相乘的简单例子,相对于其他tensorflow代码增加tf.name_scope,tf.name_scope函数是作用域名,上述代码即在graph作用域op下,又有三个op(分别是matrix1,matrix2,product),用tf函数内部的name参数命名,这样会在tensorboard中显示。

import tensorflow as tf

with tf.name_scope('graph') as scope:
     matrix1 = tf.constant([[3., 3.]],name ='matrix1')  #1 row by 2 column
     matrix2 = tf.constant([[2.],[2.]],name ='matrix2') # 2 row by 1 column
     product = tf.matmul(matrix1, matrix2,name='product')

sess = tf.Session()
writer = tf.summary.FileWriter("logs/", sess.graph) #第一个参数指定生成文件的目录。
init = tf.global_variables_initializer()
sess.run(init)

       运行上述代码后,会在logs文件夹下生成看似较为古怪,名为events.out.tfevents.1582438062.DESKTOP-3G83JN4的文件,在log文件夹所在的目录中输入tensorboard --logdir = logs(或tensorboard --logdir logs)可生成一个链接,将那个链接复制到谷歌浏览器当中即可打开。

2、keras的tensorboard举例

        当训练Keras当中的Model.fit()的时候,添加tf.keras.callbacks.TensorBoard可保证logs的创造和存储,在训练过程中,模型就进行logging data。


import tensorflow as tf
from tensorflow import keras
from tensorflow.python.keras.datasets import mnist
import datetime

mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

def create_model():
  return tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
  ])


model = create_model()
model.summary()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

log_dir2 = "logs\\func"
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir2, histogram_freq=1)

model.fit(x=x_train,
          y=y_train,
          epochs=5,
          validation_data=(x_test, y_test),
          callbacks=[tensorboard_callback])

          1)The Scalars dashboard shows how the loss and metrics change with every epoch. You can use it to also track training speed, learning rate, and other scalar values.

        2)The Graphs dashboard helps you visualize your model. In this case, the Keras graph of layers is shown which can help you ensure it is built correctly.

          3)The Distributions and Histograms dashboards show the distribution of a Tensor over time. This can be useful to visualize weights and biases and verify that they are changing in an expected way.

 

3、记录传统标量

       如果你想记录传统的数值,如动态的learning rate,需要使用tensorflow的Summary API。步骤如下:

  • 创建一个file writer,使用tf.summary.create_file_writer()
  • 定义一个常用的learning rate函数,将这一函数传递给keras中LearningRateScheduler回调函数
  • 在learning rate函数内部,使用tf.summary.scalar()来记录当下的learning rate
  • LearningRateScheduler回调函数传递给Model.fit()

       总的来说,如果你想要记录一个通用的标量,你需要在一个file writer中使用tf.summary.scalar()函数。这一个file writer就是用来记录数据。

import numpy as np
from matplotlib import pyplot as plt
from tensorflow import keras
import tensorflow as tf

# 准备数据
data_size = 1000
# 80% of the data is for training.
train_pct = 0.8
train_size = int(data_size * train_pct)

# Create some input data between -1 and 1 and randomize it.
x = np.linspace(-1, 1, data_size)
np.random.shuffle(x)

# Generate the output data.
# y = 0.5x + 2 + noise
y = 0.5 * x + 2 + np.random.normal(0, 0.05, (data_size, ))

# Split into test and train pairs.
x_train, y_train = x[:train_size], y[:train_size]
x_test, y_test = x[train_size:], y[train_size:]

plt.scatter(x_train,y_train)
plt.show()

# 创建file writer并log状态
logdir = "logs\\scalars"
file_writer = tf.summary.create_file_writer(logdir + "/metrics")
file_writer.set_as_default()

def lr_schedule(epoch):
  """
  Returns a custom learning rate that decreases as epochs progress.
  """
  learning_rate = 0.2
  if epoch > 10:
    learning_rate = 0.02
  if epoch > 20:
    learning_rate = 0.01
  if epoch > 50:
    learning_rate = 0.005

  tf.summary.scalar('learning rate', data=learning_rate, step=epoch)
  return learning_rate

lr_callback = keras.callbacks.LearningRateScheduler(lr_schedule)
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)

# 创建并训练模型
model = keras.models.Sequential([
    keras.layers.Dense(16, input_dim=1),
    keras.layers.Dense(1),
])

model.compile(
    loss='mse', # keras.losses.mean_squared_error
    optimizer=keras.optimizers.SGD(),
)

training_history = model.fit(
    x_train, # input
    y_train, # output
    batch_size=train_size,
    verbose=0, # Suppress chatty output; use Tensorboard instead
    epochs=100,
    validation_data=(x_test, y_test),
    callbacks=[tensorboard_callback, lr_callback],
)
# 预测模型
print(model.predict([60, 25, 2]))

4、记录图片(tf.summary.image)

       在指定的logdir下面创建一个记录log的文件,调用summary模块下的create_file_writer,然后通过调用tf.summary.image写入图片。

# Sets up a timestamped log directory.
logdir = "logs/train_data/"
# Creates a file writer for the log directory.
file_writer = tf.summary.create_file_writer(logdir)

# Using the file writer, log the reshaped image.
with file_writer.as_default():
  tf.summary.image("Training data", img, step=0)

       https://www.tensorflow.org/tensorboard/image_summaries

 

 

三、tensorboard如果打不开

      1、如果在调用tensorboard之后,cmd中的链接打不开的话,可以试试127.0.0.1:6006或者localhost:6006

      2、之前安装的是tensorboard2.1.0,用谷歌浏览器一直打不开,卸载了tensorboard2.1.0,然后换成tensorboard2.0.0居然可以打开了。。。

 

 

 

 

参考文献

【1】https://www.tensorflow.org/tensorboard

【2】https://www.cnblogs.com/fydeblog/p/7429344.html

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值