1.12-机器学习tensorflow框架学习-神经网络结构可视化

1.神经网络结构可视化

tensorflow使用的时候其实是一个构建神经网络结构的过程,要可视化,只需要给每个结构起个名就行了。如下

1.生成结构文件

import tensorflow as tf
def add_layer(inputs,in_size,out_size,activation_function=None):
    with tf.name_scope('layer'):
        with tf.name_scope('Weights'):
            Weights = tf.Variable(tf.random_normal([in_size,out_size]),name='W')#定义一个大小为in_size和out_size的一个权重矩阵
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1,out_size])+0.1,name='b') #定义一个1行,out_size列的偏置。一般biases不推荐为0
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs,Weights),biases)
        if activation_function is None:
            output = Wx_plus_b
        else:
            output = activation_function(Wx_plus_b)
        return output

import numpy as np
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis] #就是换成300行一列,先生成一行,再用用reshape也是一样的
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32) #给每个结果生成一点干扰
y_data = np.square(x_data)-0.5+noise

with tf.name_scope('inputs'):#这里的inputs,x_input,y_input都对应图上的名字
    xs = tf.placeholder(tf.float32,[None,1],name='x_input')#第一列,这里其实不声明这个也可以直接用x_data,但是声明了这个训练数据就是可以改的了
    ys = tf.placeholder(tf.float32,[None,1],name='y_input')
#现在假设分成三层:
#第一层输入层因为特征是1维,所以只有一个神经元,这里因为输入只有一个,输出也就一个所以假装不存在了
#第二层隐藏层,假设有十个神经元
#第三层输出层,这里只有一个输出,因此也只有一个神经元
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu) #隐藏层
prediction = add_layer(l1,10,1,activation_function=None) #输出层
with tf.name_scope("loss"):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))#定义损失函数,求平方差
with tf.name_scope('train'):
    train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#指定优化器和学习效率,作用是要减小误差
init = tf.initialize_all_variables()
sess = tf.Session()
writer = tf.summary.FileWriter("logs/",sess.graph)#指定结构日志文件输出位置
sess.run(init)
!ls -lh logs/
total 288
-rw-r--r--  1 jus4fun  staff   141K Feb 21 10:02 events.out.tfevents.1582250553.test.local

2.使用tensorboard查看日志文件

!python3 /Users/jus4fun/Library/Python/3.7/lib/python/site-packages/tensorboard/main.py --logdir="logs" --host 127.0.0.1 --port 6006
TensorBoard 1.15.0 at http://127.0.0.1:6006/ (Press CTRL+C to quit)
^C

3.访问上面地址即可查看

2.训练过程变量可视化

代码接着上面的继续改,变量可视化主要用的是histogram和sc

import tensorflow as tf
def add_layer(inputs,in_size,out_size,n_layer,activation_function=None):
    layer_name = "layer%s" % n_layer
    with tf.name_scope('layer'):
        with tf.name_scope('Weights'):
            Weights = tf.Variable(tf.random_normal([in_size,out_size]),name='W')#定义一个大小为in_size和out_size的一个权重矩阵
            tf.summary.histogram(layer_name+'/Weights',Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1,out_size])+0.1,name='b') #定义一个1行,out_size列的偏置。一般biases不推荐为0
            tf.summary.histogram(layer_name+'/biases',biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs,Weights),biases)
        if activation_function is None:
            output = Wx_plus_b
            tf.summary.histogram(layer_name+'/output',output)
        else:
            output = activation_function(Wx_plus_b)
            tf.summary.histogram(layer_name+'/output',output)
        return output

import numpy as np
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis] #就是换成300行一列,先生成一行,再用用reshape也是一样的
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32) #给每个结果生成一点干扰
y_data = np.square(x_data)-0.5+noise

with tf.name_scope('inputs'):#这里的inputs,x_input,y_input都对应图上的名字
    xs = tf.placeholder(tf.float32,[None,1],name='x_input')#第一列,这里其实不声明这个也可以直接用x_data,但是声明了这个训练数据就是可以改的了
    ys = tf.placeholder(tf.float32,[None,1],name='y_input')
#现在假设分成三层:
#第一层输入层因为特征是1维,所以只有一个神经元,这里因为输入只有一个,输出也就一个所以假装不存在了
#第二层隐藏层,假设有十个神经元
#第三层输出层,这里只有一个输出,因此也只有一个神经元
l1 = add_layer(xs,1,10,1,activation_function=tf.nn.relu) #隐藏层
prediction = add_layer(l1,10,1,2,activation_function=None) #输出层
with tf.name_scope("loss"):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))#定义损失函数,求平方差
    tf.summary.scalar("loss",loss)
with tf.name_scope('train'):
    train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#指定优化器和学习效率,作用是要减小误差
init = tf.global_variables_initializer()
sess = tf.Session()
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/",sess.graph)#指定结构日志文件输出位置
sess.run(init)
for i in range(1000):
    sess.run(train,feed_dict={xs:x_data,ys:y_data})
    if i%50==0:
        #print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
        res = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #这如果报错要shutdown
        #res = sess.run(merged,feed_dict={xs:x_data,ys:y_data})
        writer.add_summary(res,i)
!ls -lh logs/
total 264
-rw-r--r--  1 jus4fun  staff   128K Feb 21 10:55 events.out.tfevents.1582253758.test.local
!python3 /Users/jus4fun/Library/Python/3.7/lib/python/site-packages/tensorboard/main.py --logdir="logs" --host 127.0.0.1 --port 6006
TensorBoard 1.15.0 at http://127.0.0.1:6006/ (Press CTRL+C to quit)