Tensorboard
import tensorflow as tf
import numpy as np
def addlayer(inputs, insize, outsize, activation_function=None):
#add one more layer and return the output of this layer
with tf.name_scope('layer'):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([insize, outsize]),name='W') # 定义权值矩阵,一般初始值为随机数比赋全0要好
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros(outsize) + 0.1) # 在机器学习中,biases的推荐值不为0,所以我们这里是在0向量的基础上又加了0.1
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + biases # 此处矩阵乘的顺序一定要注意!!!
if activation_function is None: # 注意此处使用is
output = Wx_plus_b
else:
output = activation_function(Wx_plus_b)
return output
x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
#define placeholder for inputs to network
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')
#add hidden layer
l1 = addlayer(xs, 1, 10, activation_function=tf.nn.relu) # 隐层的输入为1(特征数),输出定义为10个神经元
#add output layer
prediction = addlayer(l1, 10, 1, None) # 输出层为1,不需要激活函数
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(prediction-ys), reduction_indices=[1]),name = 'loss')
# tf.reduce_sum()这一步相当于降维了(原来的二维数组变为了一维数组),最后可以求一维数组的平均值
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
merged =tf.summary.merge_all()
writer = tf.summary.FileWriter("D:\myjupyter\logs", sess.graph) #tf.summary.FileWriter()
sess.run(init)
实现tensorboard可视化,相较于之前代码增加内容:
with tf.name_scope('layer'): #大框架的名字
with tf.name_scope('weights'): #大框架下小零件的名字
merged =tf.summary.merge_all()
writer = tf.summary.FileWriter("D:\myjupyter\logs", sess.graph) #tf.summary.FileWriter()
#将上面保存的图添加到一个目录中(这里建立一个logs目录),graph的作用是将前面定义的东西收集起来生成文件,保存在log中!
运行
tensorboard --logdir logs
复制链接到网页…结果发现并不能打开!
一通百度之后!这样就好啦!tensorboard --logdir logs --host=127.0.0.1
C:\Users\study>activate tensorflow
(tensorflow) C:\Users\study>D:
(tensorflow) D:\>cd D:\myjupyter
(tensorflow) D:\myjupyter>tensorboard --logdir logs --host=127.0.0.1
打开网页发现:不知道为啥有两个框架(先不管它
inputs
layer
gradients
第二部分的代码参考!
https://blog.csdn.net/kudou1994/article/details/81119401?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161424187016780261951987%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=161424187016780261951987&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v29-2-81119401.first_rank_v2_pc_rank_v29&utm_term=tensorboard+%E8%8E%AB%E7%83%A6