利用tensorboard将loss,accuracy进行可视化,建立的模型也可以看到,有利于模型的调试(也可以将自定义的学习率等加进去,水平有限,这里只做了简单的介绍)
利用tensorflow中自带的数据为例,可直接下载
import tensorflow as tf
import os
from datetime import datetime
#下载数据集
(train_image,train_labels),(test_image,test_labels) = tf.keras.datasets.mnist.load_data()
train_image = tf.cast(train_image/255,tf.float32) ##转化数据类型
test_image = tf.cast(test_image/255,tf.float32)
train_labels = tf.cast(train_labels,tf.int64)
test_labels = tf.cast(test_labels,tf.int64)
##改变维度
train_image = tf.expand_dims(train_image,-1)
test_image = tf.expand_dims(test_image,-1)
#创建dataset
dataset = tf.data.Dataset.from_tensor_slices(
(train_image,train_labels))
test_dataset = tf.data.Dataset.from_tensor_slices(
(test_image,test_labels))
dataset = dataset.repeat().shuffle(10000).batch(64)
test_dataset = test_dataset.repeat().batch(64)
#模型构建
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16,[3,3], activation='relu',input_shape = (None,None,1)),
tf.keras.layers.Conv2D(32,[3,3], activation='relu'),
tf.keras.layers.GlobalMaxPooling2D(),
tf.keras.layers.Dense(10)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['acc'])
##定义回调函数
log_dir = os.path.join('填你的目录',datetime.now().strftime('%Y%m%d%-%H%M%S')) ##加入时间戳,以显示变化
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir,histogram_freq=1)
##模型训练
model.fit(dataset,epochs=15,
steps_per_epoch=60000//64,
validation_data=test_dataset,
validation_steps=10000//64,
callbacks=[tensorboard_callback])
%reload_ext tensorboard
%matplotlib inline ##tensorboard显示在当前运行框内,也可以利用cmd在网页上打开
%tensorboard --logdir /content #--logdir后加自己的目录
|