tensorboard练习
参考了这篇文章的内容https://www.cnblogs.com/fydeblog/p/7429344.html,汇总几个常用的技巧:
1 添加name_scope:为了便于graph图中能清晰的显示每个块的结构,建议在适当的位置添加自定义名称,可以在name_scope中嵌套name_scope从而清晰显示层级关系。
2 保存graph的方法, wirter = tf.summary.FileWriter('logs/',ss.graph),记录日志的位置,才能通过浏览器调用之前训练的结果
3 tf.summary.scalar记录单变量随迭代时间的变化值
tf.summary.histogram 记录向量(多变量)随迭代时间的变化值
4 启动浏览器显示界面的后台服务:Anaconda Prompt的终端输入:
tensorboard --logdir=C:\Users\vip_g\logs
浏览器输入 http://localhost:6006(tensorboard服务默认采用6006端口)
代码参照https://blog.csdn.net/weixin_41044499/article/details/94997824
# -*- coding:utf-8 -*-
# /usr/bin/python
import numpy as np
x = np.loadtxt("a.txt")
y = np.loadtxt("b.txt")
# np.savetxt("a.txt", data) # 缺省按照'%.18e'格式保存数据,以空格分隔
# np.savetxt("b.txt", y_new)
import tensorflow as tf
import numpy as np
## 原始数据
with tf.name_scope('data'):
x = np.loadtxt("a.txt")
y = np.loadtxt("b.txt")
## 创建参数,嵌套关系
with tf.name_scope('parameters'):
##权重
with tf.name_scope('weights'):
weight = tf.Variable(tf.random_uniform([1000,3],-1.0,1.0))
tf.summary.histogram('weight',weight)
##偏置
with tf.name_scope('biases'):
bias = tf.Variable(tf.zeros([1,3]))
tf.summary.histogram('bias',bias)
##get y_prediction
with tf.name_scope('y_prediction'):
predict_y = tf.nn.softmax(tf.matmul(tf.cast(x,tf.float32), weight) + bias)
##compute the loss
with tf.name_scope('loss'):
loss =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predict_y, labels=y))
tf.summary.scalar('loss',loss)
##creat optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)
#creat train ,minimize the loss
with tf.name_scope('train'):
train = optimizer.minimize(loss)
#creat init
with tf.name_scope('init'):
init = tf.global_variables_initializer()
##creat a Session
sess = tf.Session()
#merged
merged = tf.summary.merge_all()
##initialize
writer = tf.summary.FileWriter("logs/", sess.graph)
sess.run(init)
## Loop
for step in range(1000):
sess.run(train)
rs=sess.run(merged)
writer.add_summary(rs, step)
if step % 25 == 0:
correct_prediction = tf.equal(tf.argmax(predict_y, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
accuracy_value = sess.run(accuracy)
print('step:%d accuracy:%.4f' % (step, accuracy_value))