1.用try...except...避免因版本不同出现导入错误问题
try:
image_summary = tf.image_summary
scalar_summary = tf.scalar_summary
histogram_summary = tf.histogram_summary
merge_summary = tf.merge_summary
SummaryWriter = tf.train.SummaryWriter
except:
image_summary = tf.summary.image
scalar_summary = tf.summary.scalar
histogram_summary = tf.summary.histogram
merge_summary = tf.summary.merge
SummaryWriter = tf.summary.FileWriter
2. 将代码写入作用域(作用域不影响代码的运行)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)
# Evaluate model
accuracy=tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1),tf.argmax(y,1)),"float"))
# accuracy=correct_prediction/170000
#use tensorboard
loss_summary = scalar_summary('loss', cost)
acc_summary = scalar_summary('accuracy', accuracy)
3.将要保存的变量存在一起
另外可使用 tf.merge_all_summaries() 或者 tf.summary.merge_all()
merged = merge_summary([loss_summary,acc_summary])
只需要输出loss:merged = merge_summary([loss_summary])
4.定义保存路径(在sess中完成,写在迭代之前),其中/home/qiaobo/文档/bilstm_CoNLL2003_8_100为保存日志的路径
writer = SummaryWriter('/home/qiaobo/文档/bilstm_CoNLL2003_8_100', sess.graph)
5.训练模型的同时训练变量集合merged(在sess中完成,counter为计数,每训练一次增加1)
summary,accuracy_,loss_value = sess.run([merged,accuracy,cost],feed_dict={x:np.reshape(test_words,(-1,n_steps,n_inputs)),y:np.reshape(test_tags,(-1,n_tags))})
counter += 1
writer.add_summary(summary, counter)
6. 在bilstm_CoNLL2003_8_100文件下可以看到一个生成的日志事件
7. 运行Tensorboard
(1)cd 到bilstm_CoNLL2003_8_100文件夹的上一级目录
(2)输入命令行: tensorboard --logdir=bilstm_CoNLL2003_8_100
(3)回车,就自动加载。注意:最下面黄色线的那个网址,你复制网址到Chrome浏览器中就可以打开TensorBoard。
一般为:http://ip:6006
常见错误:
1.ERROR:tensorflow:TensorBoard attempted to bind to port 6006, but it was already in use
TensorBoard attempted to bind to port 6006, but it was already in use
解决方法:(1)命令行:lsof -i:6006
(2)命令行:kill -9 pid
(3) 命令行:tensorboard --logdir /home/qiaobo/文档/bilstm_CoNLL2003_8_100