使用手写体数据集
导入库
import numpy as np
from tensorflow import keras
from keras.layers import Input, Dense, Dropout, Activation,Conv2D,MaxPool2D,Flatten
from keras.datasets import mnist
from keras.models import Model
from tensorflow.python.keras.utils.np_utils import to_categorical
from keras.callbacks import TensorBoard
建立模型
(x_train,y_train),(x_test,y_test) = mnist.load_data()
x_train=np.expand_dims(x_train,axis=-1)
x_test=np.expand_dims(x_test,axis=-1)
y_train=to_categorical(y_train,num_classes=10)
y_test=to_categorical(y_test,num_classes=10)
batch_size=128
epochs=1
inputs = Input([28,28,1])
x = Conv2D(32, (5,5), activation=‘relu‘)(inputs)
x = Conv2D(64, (5,5), activation=‘relu‘)(x)
x = MaxPool2D(pool_size=(2,2))(x)
x = Flatten()(x)
x = Dense(128, activation=‘relu‘)(x)
x = Dropout(0.5)(x)
x = Dense(10, activation=‘softmax‘)(x)
model = Model(inputs,x)
定义优化参数
model.compile(loss=‘categorical_crossentropy‘, optimizer="adam",metrics=[‘acc‘])
导入tensorboard
from tensorflow.keras.callbacks import TensorBoard
定义tensorflow 参数
tbCallBack = TensorBoard(log_dir=‘./log‘, histogram_freq=1,
write_graph=True,
write_grads=True,
batch_size=batch_size,
write_images=True)
模型训练,并将评价参数传回callback
bistory=model.fit(x_train, y_train,
batch_size=batch_size,
epochs=1,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[tbCallBack])
WARNING:tensorflow:`write_grads` will be ignored in TensorFlow 2.0 for the `TensorBoard` Callback.
WARNING:tensorflow:`batch_size` is no longer needed in the `TensorBoard` Callback and will be ignored in TensorFlow 2.0.
469/469 [==============================] - 217s 460ms/step - loss: 2.5759 - acc: 0.8084 - val_loss: 0.0620 - val_acc: 0.9825
%load_ext tensorboard
#使用tensorboard 扩展
%tensorboard --logdir logs
#定位tensorboard读取的文件目录
# logs是存放tensorboard文件的目录
The tensorboard extension is already loaded. To reload it, use:
%reload_ext tensorboard
Reusing TensorBoard on port 6006 (pid 103), started 0:58:49 ago. (Use ‘!kill 103‘ to kill it.)
<IPython.core.display.Javascript object>
## https://zhuanlan.zhihu.com/p/109638819
# https://blog.csdn.net/weixin_44791964/article/details/105002793