tensorflow学习5:使用tensorboard可视化loss,weight,biases

这一次的可视化任务和上一次的可视化差不多,只是增加了一些可视化项,不仅仅是网络结构。

我们还是在前面搭建的网络结构上进行修改,大家对这个也比较熟悉了。

第一步还是准备数据:

import tensorflow as tf
import numpy as np
 
#构造数据
x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis] #在-1 到 1之间生成300个数据,
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32) #增加 noise项目,给数据增加一些波动
y_data = np.square(x_data) - 0.5 + noise #数据的
 
#采用占位符为变量预定义位置 None 代表后面无论输入多少特征都可以
with tf.name_scope("inputs"):
    xs=tf.placeholder(tf.float32,[None , 1],name="x_input")
    ys=tf.placeholder(tf.float32,[None , 1],name="y_input")

第二步定义网络:

我们要绘制图表主要依赖的是tf.histogram_summary()方法,用来绘制图片, 第一个参数是图表的名称, 第二个参数是图表要记录的变量。在每一个要记录的变量下使用这个函数。

def add_layer(inputs , in_size, out_size,n_layer, activation_function=None):
    ## add one more layer and return the output of this layer
    layer_name='layer%s'%n_layer
    with tf.name_scope(layer_name):
         with tf.name_scope('weights'):
              Weights= tf.Variable(tf.random_normal([in_size, out_size]),name='W')
              tf.summary.histogram(layer_name + '/weights', Weights) # tensorflow >= 0.12

         with tf.name_scope('biases'):
              biases = tf.Variable(tf.zeros([1,out_size])+0.1, name='b')
             
              tf.summary.histogram(layer_name + '/biases', biases)  # Tensorflow >= 0.12

         with tf.name_scope('Wx_plus_b'):
              Wx_plus_b = tf.add(tf.matmul(inputs,Weights), biases)

         if activation_function is None:
            outputs=Wx_plus_b
         else:
            outputs= activation_function(Wx_plus_b)

         
         tf.summary.histogram(layer_name + '/outputs', outputs) # Tensorflow >= 0.12

    return outputs

第三步定义网络和loss可视化:

可视化loss使用的是和前面不同的方式tf.scalar_summary() 

#build network
#构建一个输入层一个神经元,隐含层都是10个神经元,输出层1个神经元的神经网络
l1=add_layer(xs,1,10,n_layer=1,activation_function=tf.nn.relu)
prediction=add_layer(l1,10,1,n_layer=2)
 
#定义损失函数
with tf.name_scope("loss"):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))
    tf.summary.scalar("loss",loss)
#定义优化器
optimizer=tf.train.AdamOptimizer(0.1).minimize(loss)
 
#初始化变量
init=tf.global_variables_initializer()

第四步就是运行网络,并合并各个图:

使用tf.summary.merge_all() 对不同的图进行合并,merge 也是必须要运行才会生效。我们每隔一百次就使用merge记录一下数据,如果不是不停的记录数据,最后也是没有图出来的。

#定义好各种运算操作后,放到Session中进行
with tf.Session() as sess:
    sess.run(init)  # 变量一定要进行初始化
    merged = tf.summary.merge_all() 
    writer = tf.summary.FileWriter("loss_log/", sess.graph)
    for i in range(1000):
        sess.run(optimizer,feed_dict={xs:x_data,ys:y_data}) #训练对应的优化器
        if i%100==0:
            print(sess.run(loss, feed_dict={xs: x_data, ys: y_data})) 
            rs = sess.run(merged,feed_dict={xs:x_data,ys:y_data})
            writer.add_summary(rs, i)
            #每一百步打印一下对应的损失

 

效果:

loss:

weight、biases:

网络结构:

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorBoardTensorFlow的一个可视化工具,可以帮助我们更好地理解和调试TensorFlow模型。 下面是一个简单的TensorBoard可视化实例: 1.导入必要的库和数据集 ```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) ``` 2.定义一个简单的三层神经网络模型 ```python with tf.name_scope("input"): x = tf.placeholder(tf.float32, [None, 784], name="x-input") y = tf.placeholder(tf.float32, [None, 10], name="y-input") with tf.name_scope("layer"): with tf.name_scope("weights"): W = tf.Variable(tf.zeros([784, 10]), name="W") with tf.name_scope("biases"): b = tf.Variable(tf.zeros([10]), name="b") with tf.name_scope("softmax"): y_pred = tf.nn.softmax(tf.matmul(x, W) + b) ``` 3.定义交叉熵损失函数和优化器 ```python with tf.name_scope("loss"): cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1])) tf.summary.scalar("loss", cross_entropy) with tf.name_scope("train"): train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) ``` 4.定义准确率计算 ```python with tf.name_scope("accuracy"): correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar("accuracy", accuracy) ``` 5.合并所有的summary ```python merged_summary = tf.summary.merge_all() ``` 6.定义Session和FileWriter来保存summary ```python with tf.Session() as sess: writer = tf.summary.FileWriter("logs/", sess.graph) sess.run(tf.global_variables_initializer()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) _, summary = sess.run([train_step, merged_summary], feed_dict={x: batch_xs, y: batch_ys}) writer.add_summary(summary, i) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})) ``` 7.在终端中运行以下命令以启动TensorBoard ```bash tensorboard --logdir=logs/ ``` 8.在浏览器中打开http://localhost:6006/,即可看到TensorBoard可视化结果。 这个例子中,我们使用TensorBoard可视化模型的损失函数和准确率的变化,以及模型结构的图形化展示。通过TensorBoard可视化,我们可以更加直观地了解模型的训练过程和性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值