环境:
- tensorflow2.0
- jupyter notebook
- unbuntu18.04(这个应该影响不大)
示例:
用的是iris数据集分类,该数据集库自带。
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
data = load_iris()
iris_target = data.target
iris_data = np.float32(data.data)
# one-hot,标签
iris_target = np.float32(tf.keras.utils.to_categorical(iris_target,num_classes=3))
inputs_xs = tf.keras.Input(shape=(4),name='input_xs')
out = tf.keras.layers.Dense(32,activation='relu',name='dense_1')(inputs_xs)
out = tf.keras.layers.Dense(64,activation='relu',name='dense_2')(out)
logits = tf.keras.layers.Dense(3,activation='softmax',name='predictions')(out)
model = tf.keras.Model(inputs = inputs_xs,outputs=logits)
model.compile(optimizer=tf.optimizers.Adam(1e-3),
loss = tf.losses.categorical_crossentropy,
metrics=['accuracy'])
下面是使用tensorboard重点
import datetime #datetime模块提供用于处理日期和时间的类,引入
# datetime模块主要是为了能够进行可视化区分,假如我们要训练好几次网络,每次时间不同,
# 引入这个模块后就可以在tensorboard可视化界面中记录每次所训练的结果,方便对照
#写入路径
import os
log_dir=os.path.join('logs',datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))#在tensorboard可视化界面中会生成带时间标志的文件
tensorboard_callback=tf.keras.callbacks.TensorBoard(log_dir,histogram_freq=1)#回调tensorflow自带的tensorboard
model.fit(x=iris_data,
y=iris_target,
batch_size=128,
epochs=500,
callbacks=[tensorboard_callback]
)
训练完成后~
%load_ext tensorboard ##这行代码加载tensorboard
%matplotlib inline #在线可视化
%tensorboard --logdir logs #加载生成的logs 文件load_ext tensorboard #这行代码加载tensorboard
即可调出Tensorboard信息 备注: 在调用tensorboard是可能出现问题:
ERROR: Could not find `tensorboard`. Please ensure that your PATH
contains an executable `tensorboard` program, or explicitly specify
the path to a TensorBoard binary by setting the `TENSORBOARD_BINARY`
environment variable.
解决: 缺少环境配置问题,添加一行配置即可
%load_ext tensorboard ##这行代码加载tensorboard
%matplotlib inline #在线可视化
os.environ['TENSORBOARD_BINARY'] = '/path/to/envs/my_env/bin/tensorboard'#这里' '里面要填写自己所用虚拟环境下的tensorboard路径
%tensorboard --logdir logs #加载生成的logs 文件load_ext tensorboard #这行代码加载tensorboard
|