Tensorboard可视化好帮手2

来源:互联网 发布:sqlserver 大数据导入 编辑:程序博客网 时间:2024/05/21 19:39

代码来自莫烦的优酷播单:

莫凡 tensorflow 神经网络 教程:Tensorflow 15 Tensorboard可视化好帮手2


因为Tensorflow现在已经更新到1.0版本了,视频演示里的代码有部分函数需要修改

更新之后的代码如下:


import tensorflow as tfimport numpy as npdef add_layer(inputs, in_size, out_size, n_layer, activation_function=None):#activation_function=None表示没有激活函数  相当于是线性模型layer_name = 'layer%s' % n_layerwith 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)with tf.name_scope('biases'):biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name = 'b')#偏置最好不为零所以加了0.1tf.summary.histogram(layer_name+'/biases', biases)with tf.name_scope('Wx_plus_b'):Wx_plus_b = tf.matmul(inputs, Weights) + biasesif activation_function is None:outputs = Wx_plus_belse:outputs = activation_function(Wx_plus_b)tf.summary.histogram(layer_name+'/outputs', outputs)return outputs# 真实数据x_data = np.linspace(-1,1,300)[:,np.newaxis]#None表示可以输入任意的数据noise = np.random.normal(0, 0.05, x_data.shape)# 输入一个均值为0,方差为0.05的高斯噪声,与x_data有相同的shapey_data = np.square(x_data) - 0.5 + noise# 定义神经网络输入的placeholderwith tf.name_scope('inputs'):xs = tf.placeholder(tf.float32,[None,1], name = "x_input")#None表示可以输入任意的数据。因为x_data是300x1的矩阵,所以这里为[None,1]ys = tf.placeholder(tf.float32,[None,1], name = 'y_input')#隐藏层layer1 输入节点1,输出节点10l1 = add_layer(xs, 1, 10, n_layer=1, activation_function = tf.nn.relu)#预测的时候输入时隐藏层的输入l1,输入节点10,输出为y_data 有1个节点prediction = add_layer(l1, 10, 1, n_layer=2, activation_function = None)#计算损失with tf.name_scope('loss'):loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices = [1]))#loss是一个纯量的变化,所以不是用histogr。会在SCALARS里显示tf.summary.scalar('loss',loss)with tf.name_scope('train'):train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)init = tf.global_variables_initializer()sess = tf.Session()merged = tf.summary.merge_all()writer = tf.summary.FileWriter("C:/Users/zhs/Desktop/TensorFlow/mofan/",sess.graph)# 先加载到一个文件中,然后再加载到浏览器里观看sess.run(init)#只有run的时候才执行,所以第一步是先激活所有变量for i in range(1000):sess.run(train_step, feed_dict={xs:x_data,ys:y_data})if i%50 == 0:result = sess.run(merged, feed_dict={xs:x_data,ys:y_data})writer.add_summary(result, i)



在Tensorboard里显示的结果就是这样的:
0 0
原创粉丝点击