tensorflow之神经网络层添加函数

来源:互联网 发布:php格式的图片怎么打开 编辑:程序博客网 时间:2024/06/05 04:30

这一篇文章是对神经网络的一个深入探索,虽然都是简单的例子,但是足以了解神经网络的架构。
一、包含一个隐含层的网络实现
1.定义添加层函数
在前面的浅层神经网络(http://blog.csdn.net/xuan_zizizi/article/details/77799868)里面不涉及隐含层,只有输入输出层,而这篇文章将继续描述如何为神经网络添加新的层,以及如何定义添加层的函数。

#encoding=utf-8import tensorflow as tfdef add_layer(inputs,in_size,out_size,activation_function=None): #添加一个层,输入值,输入尺寸,输出尺寸,以及激励函数,此处None默认为线性的激励函数    w_pre = tf.Variable(tf.random_normal([in_size,out_size])) #定义权值矩阵,in_size行,out_size列,随机初始权值    b_pre = tf.Variable(tf.zeros([1,out_size])+0.1) #定义一个列表,一行,out_size列,值全部为0.1    y_pre = tf.matmul(inputs,w_pre)+b_pre  #w_pre*inputs+b_pre,预测值,未激活    if activation_function is None        outputs = y_pre #结果为线性输出,激活结果    else:        outputs = activation_function(y_pre)#激励函数处理    return outputs

2.定义数据集
这里可以定义随机数据,通过神经网络学习来完成线性拟合功能。

#定义数据集x_real = np.linspace(-1,1,300)[:,np.newaxis]#[-1,1]之间有300个值,后面[]表示维度,即有300行noise = np.random.normal(0,0.05,x_real.shape)#噪声均值为0,方差为0.05,与x_data格式相同y_real = np.square(x_real)-0.5 + noise#定义placeholder接收数据xs = tf.placeholder(tf.float32,[None,1],name='x_input')ys = tf.placeholder(tf.float32,[None,1],name='y_input')

3.定义隐含层,神经元数目为10

#隐含层输入层input(1个神经元):输入1个神经元,隐藏层10个神经元l1 = add_layer(xs,1,10,activation_function = tf.nn.relu)

4.定义输出层,隐含层l1的输出为输出层predicti里写代码片输出层

prediction = add_layer(l1,10,1,activation_function = None)#输出层也是1个神经元

5.定义loss函数

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))#先求误差平方和的和求平均,reduce_sum表示对矩阵求和,reduction_indices=[1]方向

6.选择合适的优化器来优化训练过程的损失函数

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#学习效率0.1,要求小于1

7.初始化变量

init = tf.initialize_all_variables()#初始化所有变量sess = tf.Session()sess.run(init)#激活

8.可视化结果

#可视化结果fig = plt.figure()ax = fig.add_subplot(1,1,1)ax.scatter(x_real,y_real)plt.ion()plt.show()

9.迭代
通过迭代更新权值和偏移

for i in range(1000):    sess.run(train_step,feed_dict = {xs:x_real,ys:y_real})    if i%50 == 0:        try:            ax.lines.remove(lines[0])        except Exception:            pass        prediction_value = sess.run(prediction,feed_dict={xs:x_real})        #画出预测        lines = ax.plot(x_real,prediction_value,'r-',lw=2)        plt.pause(1)

10.建造一个简单的神经网络
完成了层添加函数之后,则要用层添加函数搭建一个神经网络,通过添加层函数来为神经网络增加隐含层,以下为完整的可执行代码:

#encoding=utf-8import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt#定义一个方法用于添加层def add_layer(inputs,in_size,out_size,activation_function = None):    Weights = tf.Variable(tf.random_normal([in_size,out_size]),name='w')    biases = tf.Variable(tf.zeros([1,out_size])+0.1,name='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)    return outputs#定义数据集x_real = np.linspace(-1,1,300)[:,np.newaxis]#[-1,1]之间有300个值,后面[]表示维度,即有300行noise = np.random.normal(0,0.05,x_real.shape)#噪声均值为0,方差为0.05,与x_data格式相同y_real = np.square(x_real)-0.5 + noisexs = tf.placeholder(tf.float32,[None,1],name='x_input')ys = tf.placeholder(tf.float32,[None,1],name='y_input')#建造第一层输入层input(1个神经元):输入1个神经元,隐藏层10个神经元l1 = add_layer(xs,1,10,activation_function = tf.nn.relu)#输出层prediction = add_layer(l1,10,1,activation_function = None)#输出层也是1个神经元loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))#先求误差平方和的和求平均,reduce_sum表示对矩阵求和,reduction_indices=[1]方向train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#学习效率0.1,要求小于1init = tf.initialize_all_variables()#初始化所有变量sess = tf.Session()sess.run(init)#激活#可视化结果fig = plt.figure()ax = fig.add_subplot(1,1,1)ax.scatter(x_real,y_real)plt.ion()plt.show()for i in range(1000):    sess.run(train_step,feed_dict = {xs:x_real,ys:y_real})    if i%50 == 0:        try:            ax.lines.remove(lines[0])        except Exception:            pass        prediction_value = sess.run(prediction,feed_dict={xs:x_real})        #画出预测        lines = ax.plot(x_real,prediction_value,'r-',lw=2)        plt.pause(1)

二、可视化计算图操作
(一)查看神经网络结构图
1.为Graph中的Tensor添加层级
(1)添加名为Weights的层级

with tf.name_scope('Weights')

(2)historygram功能
想要看某个变量的变化则加入以下语句,如,以Weights变量为例

tf.historygram_summary(layer_name+'/weight',Weights)merged = tf.merge_all_summaries()#合并,打包所有的变量跟踪

(3)loss功能
tf.scalar_summary(‘loss’)
(二)其中涉及到的函数解释:
(1)Summary:所有需要在TensorBoard上面展示的统计结果
(2)tf.name_scope():为Graph中的Tensor添加层级,TensorBoard会按照代码指定的层级进行展示,初始状态下为最高层级,可点击展开下一层细节。
(3)tf.summary.scalar():添加统计结果。
(4)tf.summary.histogram():添加任意形状的Tensor,统计其取值分布。
(5)tf.summary.merge_all():添加一个操作,代表执行所有的summary,避免人工执行每个summary操作。
(6)tf.summary.FileWrite():将Summary写入磁盘,需要指定存储路径logdir;执行summary操作后,将返回结果传递给add_summary即可。
(三)实际的程序实现,以一中的10的程序为例,给出如下的程序演示:

#encoding=utf-8import tensorflow as tfimport numpy as np#定义层def add_layer(inputs, in_size,out_size, n_layer, activation_function=None):    #添加多个层,用n计数    layer_name = 'layer%s' % n_layer    with tf.name_scope(layer_name):#一级,第n个层        with tf.name_scope('weights'):#二级,权值            Weights =tf.Variable(tf.random_normal([in_size, out_size]), name='W')           tf.histogram_summary(layer_name + '/weights', Weights) #总结第n层的权值变量变化        with tf.name_scope('biases'):#二级,偏差            biases = tf.Variable(tf.zeros([1,out_size]) + 0.1, name='b')           tf.histogram_summary(layer_name + '/biases', biases) #总结第n层的偏差变量变化        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.histogram_summary(layer_name +'/outputs', outputs) #总结第n层的输出变量变化        return outputs# 产生数据x_real = np.linspace(-1, 1, 300)[:, np.newaxis]noise = np.random.normal(0, 0.05, x_real.shape)y_real = np.square(x_real) - 0.5 + noise# 定义传入值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')# 添加隐藏层l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)# 添加输出层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]))    tf.scalar_summary('loss', loss)#显示误差变化情况,但是和其他变量跟踪不一样with tf.name_scope('train'):#一级,训练    train_step =tf.train.GradientDescentOptimizer(0.1).minimize(loss)sess = tf.Session()merged = tf.merge_all_summaries()  #合并summary,方便一次性操作所有的summarywriter = tf.train.SummaryWriter("logs/",sess.graph)#将graph文件写入文件夹# 激活sess.run(tf.initialize_all_variables())#打印结果for i in range(1000):    sess.run(train_step, feed_dict={xs:x_real, ys: y_real})    if i % 50 == 0:        result = sess.run(merged,                          feed_dict={xs:x_real, ys: y_real}) #运行merged        writer.add_summary(result, i)        #把merged里面的summaries放到writer里面

(四)读取tensorboard的结果:

tensorboard --logdir='logs/' #显示你保存架构文件的文件夹logs

运行之后会得到一个网址:http://0.0.0.0:6006
在谷歌浏览器打开(不过现在好像不能使用这个网址了),打开网址,点开graph

原创粉丝点击