简介
- tensorboard 是tensorflow的一个可视化工具,可以简便看网络图、loss等评估指标曲线。
使用方法
- 1、首先要用tf.summary.scalar(name, variable)创建一个节点,用于保存这一层的权重,name是新建节点名称,val=variable是网络图中变量名。
- 2、利用 tf.summary.FileWriter(filepath, graph) 来保存所有节点信息,filepath是权重文件名称,graph是要保存的图
- 3、利用新建节点的方法:add_summary方法将在训练或测试时候把对应权重写入文件。
- 4、关闭文件: close()
训练完,用下面命令使得数据在浏览器可视化
tensorboard --logdir filepath --port port_number
eg.
tensorboard --logdir tf_logs/ --port 7007
例子
import tensorflow as tf
import os
os.environ['CUDA_VISIBLE_DEVICES']='0' #set gpu mode
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.1
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing()
m, n = housing.data.shape
scaler = StandardScaler()
scaled_housing_data = scaler.fit_transform(housing.data)
scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]
from datetime import datetime
now = datetime.utcnow().strftime("%Y%m%d%H%M%S") # log path
root_logdir = "tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now) # log name
n_epochs = 1000
learning_rate = 0.01
X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(mse)
init = tf.global_variables_initializer()
mse_summary = tf.summary.scalar('MSE', mse) # init scalar
file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) # new file
n_epochs = 10
batch_size = 100
n_batches = int(np.ceil(m / batch_size))
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
for batch_index in range(n_batches):
X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
if batch_index % 10 == 0:
summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch})
step = epoch * n_batches + batch_index
file_writer.add_summary(summary_str, step) # add
sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
best_theta = theta.eval()
file_writer.close()
