Bootstrap

【笔记】keras中调用TensorBoard:读取训练日志

(一)前 言

        Tensorboard是TensorFlow自带的一款强大的可视化工具,作为TensorFlow的一大“门面”,它可以对模型的训练过程进行十分生动地可视化,Tensorboard非常好用,当我们使用Keras以TensorFlow作为backend时,我们也可以通过callback方法调用它:

import keras.callbacks
tb_config = keras.callbacks.TensorBoard(
    log_dir='./logs', # 日志文件保存位置
    histogram_freq=0, # 计算各个层激活值直方图的频率(每多少个epoch计算一次),如果设置为0则不计算。
    batch_size=32, # 计算直方图的批处理数
    write_graph=True,# 是否在tensorboard中可视化计算图
    write_grads=False, # 是否在tensorboard中可视化梯度直方图
    write_images=False, # 是否写入模型权重以在tensorboard以图像形式进行可视化
    embeddings_freq=0, # 下列四个关于embedding的参数不常用,在此不做解释
    embeddings_layer_names=None,
    embeddings_metadata=None,
    embeddings_data=None,
    update_freq='batch' # 更新频率)

 

(二)示例代码

import keras.callbacks
import numpy as np
import tensorflow as tf
from keras.datasets import mnist
from keras.layers.core import Activation, Dense, Dropout
from keras.models import Sequential
from keras.optimizers import SGD
from keras.utils import np_utils

# 导入数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1] * X_train.shape[2])
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1] * X_test.shape[2])
X_train = X_train.astype(np.float32)
X_train /= 255
X_test = X_test.astype(np.float32)
X_test /= 255
# 标签数据one-hot化
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

# 定义模型
model = Sequential()
model.add(Dense(512, input_shape=(784,), init='normal', name='dense1'))
model.add(Activation('relu', name='relu1'))
model.add(Dropout(0.2, name='dropout1'))
model.add(Dense(512, init='normal', name='dense2'))
model.add(Activation('relu', name='relu2'))
model.add(Dropout(0.2, name='dropout2'))
model.add(Dense(10, init='normal', name='dense3'))
model.add(Activation('softmax', name='softmax1'))
model.summary()
 
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), metrics=['accuracy'])
 
tb_config = keras.callbacks.TensorBoard(
    log_dir= 'C:/Users/12394/PycharmProjects/Keras/logs',
    write_images= 1,
    histogram_freq= 1)

cbks = [tb_config]
history = model.fit(
    X_train, Y_train,
    batch_size= 128,
    epochs= 3,
    verbose= 1,
    callbacks= cbks,
    validation_data= (X_test, Y_test))

model.evaluate(X_test, Y_test, verbose= 1)

# 输出:
Epoch 1/3
60000/60000 [==============================] - 4s 73us/step - loss: 2.1546 - acc: 0.2693 - val_loss: 1.9333 - val_acc: 0.5596
Epoch 2/3
60000/60000 [==============================] - 6s 92us/step - loss: 1.8351 - acc: 0.5164 - val_loss: 1.6099 - val_acc: 0.7067
Epoch 3/3
60000/60000 [==============================] - 5s 90us/step - loss: 1.5474 - acc: 0.6314 - val_loss: 1.3154 - val_acc: 0.7660

   

(三)读取训练日志

使用以下命令读取日志:

tensorboard.exe --logdir="你的日志保存位置"

如下图所示:
在这里插入图片描述

 

;