添加关键代码
在模型训练语句中添加回传训练信息的代码
# 每隔一个训练循环就用柱状图显示信息
callbacks = [keras.callbacks.TensorBoard(log_dir='自定义日志保存目录'.format(模型名称))]
history = fashion_model.fit(训练集, 标签, epochs, batch_size, validation_split = 0.2, callbacks = callbacks)
训练模型
# 运行你的训练代码
>> python XXX.py
打开TensorBoard
>> tensorboard --logdir='自定义日志保存目录'
# 出现形如以下的提示,打开链接查看
TensorBoard 1.14.0 at http://harvest07:6006/ (Press CTRL+C to quit)
示例代码
import keras;
from keras import layers
from keras.datasets import fashion_mnist
from keras.preprocessing import sequence
from keras.utils import to_categorical
from keras.models import Sequential,Input,Model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
batch_size = 128
num_classes = 10
epochs = 20
(train_X, train_Y), (test_X, test_Y) = fashion_mnist.load_data()
train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)
train_X = train_X.astype('float32')
test_X = test_X.astype('float32')
train_X = train_X / 255.
test_X = test_X / 255.
train_Y_one_hot = to_categorical(train_Y)
test_Y_one_hot = to_categorical(test_Y)
fashion_model = Sequential()
fashion_model.add(Conv2D(32, kernel_size=(3, 3),activation='linear',padding='same',input_shape=(28,28,1)))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D((2, 2),padding='same'))
fashion_model.add(Dropout(0.25))
fashion_model.add(Conv2D(64, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Dropout(0.25))
fashion_model.add(Conv2D(128, (3, 3), activation='linear',padding='same'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same'))
fashion_model.add(Dropout(0.4))
fashion_model.add(Flatten())
fashion_model.add(Dense(128, activation='linear'))
fashion_model.add(LeakyReLU(alpha=0.1))
fashion_model.add(Dropout(0.3))
fashion_model.add(Dense(num_classes, activation='softmax'))
fashion_model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.Adam(),metrics = ['accuracy'])
# fashion_model.summary() #visualize the layers
# 每隔一个训练循环就用柱状图显示信息
callbacks = [keras.callbacks.TensorBoard(log_dir='./keras_log'.format(fashion_model))]
history = fashion_model.fit(train_X, train_Y_one_hot, epochs = 20, batch_size = 128, validation_split = 0.2, callbacks = callbacks)