Tensorflow入门-实现神经网络

来源:互联网 发布:网站sql注入检测 编辑:程序博客网 时间:2024/05/19 14:16


学习tensorflow一段时间了,感觉非常的好用,在使用时,有时候最重要的是想好神经网络的结构,这样就可以随意的在神经网络中加如隐含层了,特别主要的是矩阵的维度相乘的问题,下面将使用tensorflow实现神经网络,做一下自己的理解.

实现无隐含层的神经网络

下面以手写数字识别的例子作为说明.

读入数据

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

查看数据情况: 
分为训练数据,验证数据和测试数据三类.

print mnist.train.images.shape      print mnist.train.labels.shapeprint mnist.test.images.shapeprint mnist.test.labels.shapeprint mnist.validation.images.shapeprint mnist.validation.labels.shape########################这里有55000*784,784为每一个图片的维度,被拉成一个长的向量(55000, 784)(55000, 10)(10000, 784)(10000, 10)(5000, 784)(5000, 10)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这里注意一下,输入训练的x为 n*784 ,w 为 784*10 输出的y为: n*10,即每一个行向量有10个列,表示了其代表0,1…9的概率值.

x = tf.placeholder(tf.float32,[None,784])其表示,在进行run的时候才读入数据. 
y = tf.nn.softmax(tf.matmul(x,W)+b) softmax为转出每个标签的概率,表示预测的结果.其公式为: 

softmaxi=exp(xi)jexp(xj)

可以看到,只不过对输出做了一个概率上的统计而已.

预测作为了,我们还需要一个损失函数,传递误差,所用的损失函数为交叉熵损失: 

H=ylog(y)

其中y为真实的值,y’为预测的值

注意reduce_sum的使用:

这里写图片描述
图片来源:知乎

reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1])) 
所以此语句的意思是将每一个样本的损失加起来,然后在用reduce_mean()求平均.因为y,y’都为1*10的向量,这是要注意的.

接下来就是要定义训练的方式,采用梯度下降,来最小话交叉熵. 
tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.InteractiveSession()#real datax = tf.placeholder(tf.float32,[None,784])y_ = tf.placeholder(tf.float32,[None,10])W = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))#predicty = tf.nn.softmax(tf.matmul(x,W)+b)#loss cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))#train waystrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

进行训练

##重点,全局参数初始化tf.global_variables_initializer().run()  ##迭代1000次,每次取出100个样本进行训练SGDfor i in range(1000):    batch_x,batch_y = mnist.train.next_batch(100)    train_step.run({x:batch_x,y_:batch_y})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

train_step.run({x:batch_x,y_:batch_y})这种方式为在运行的时候,feed_dict给x,y_的值,其中x为训练样本,y_为对应的真值.

评估

#testcorrect_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_meanprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels})
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

最终的结果为:0.9174

实现多层神经网络

为了方便的添加层,写一个添加层的函数,其中in_size,out_size都为神经元的尺度,input为上一层的输出,output为这一层的输出.

完整代码如下:

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/",one_hot=True)sess = tf.InteractiveSession()#定义添加隐含层的函数def add_layer(inputs, in_size, out_size,keep_prob=1.0,activation_function=None):    Weights = tf.Variable(tf.truncated_normal([in_size,out_size],stddev=0.1))    biases = tf.Variable(tf.zeros([out_size]))    Wx_plus_b = tf.matmul(inputs, Weights) + biases    if activation_function is None:        outputs = Wx_plus_b    else:        outputs = activation_function(Wx_plus_b)        outputs = tf.nn.dropout(outputs,keep_prob)  #随机失活    return outputs# holder变量x = tf.placeholder(tf.float32,[None,784])y_ = tf.placeholder(tf.float32,[None,10])keep_prob = tf.placeholder(tf.float32)     # 概率h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)##输出层w = tf.Variable(tf.zeros([300,10]))     #300*10b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(h1,w)+b)#定义loss,optimizercross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))train_step  =tf.train.AdagradOptimizer(0.35).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_meantf.global_variables_initializer().run()for i in range(3000):    batch_x,batch_y  = mnist.train.next_batch(100)    train_step.run({x:batch_x,y_:batch_y,keep_prob:0.75})    if i%1000==0:        train_accuracy = acuracy.eval({x:batch_x,y_:batch_y,keep_prob:1.0})        print("step %d,train_accuracy %g"%(i,train_accuracy))###########testprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

运行上述程序,得到正确为:0.9784,而这仅仅是加了一个隐含层而已. 
上面的隐含层的节点加的是300个神经元,如果要再加上一层400个神经元的非常的简单.

h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)h2 = add_layer(h1,300,400,keep_prob,tf.nn.relu)##输出层w = tf.Variable(tf.zeros([400,10]))     #300*10b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(h2,w)+b)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看到,你可以随意的添加隐含的节点,和节点的个数,需要注意的是,维度不要搞错就行了.

学习tensorflow一段时间了,感觉非常的好用,在使用时,有时候最重要的是想好神经网络的结构,这样就可以随意的在神经网络中加如隐含层了,特别主要的是矩阵的维度相乘的问题,下面将使用tensorflow实现神经网络,做一下自己的理解.

实现无隐含层的神经网络

下面以手写数字识别的例子作为说明.

读入数据

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

查看数据情况: 
分为训练数据,验证数据和测试数据三类.

print mnist.train.images.shape      print mnist.train.labels.shapeprint mnist.test.images.shapeprint mnist.test.labels.shapeprint mnist.validation.images.shapeprint mnist.validation.labels.shape########################这里有55000*784,784为每一个图片的维度,被拉成一个长的向量(55000, 784)(55000, 10)(10000, 784)(10000, 10)(5000, 784)(5000, 10)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这里注意一下,输入训练的x为 n*784 ,w 为 784*10 输出的y为: n*10,即每一个行向量有10个列,表示了其代表0,1…9的概率值.

x = tf.placeholder(tf.float32,[None,784])其表示,在进行run的时候才读入数据. 
y = tf.nn.softmax(tf.matmul(x,W)+b) softmax为转出每个标签的概率,表示预测的结果.其公式为: 

softmaxi=exp(xi)jexp(xj)

可以看到,只不过对输出做了一个概率上的统计而已.

预测作为了,我们还需要一个损失函数,传递误差,所用的损失函数为交叉熵损失: 

H=ylog(y)

其中y为真实的值,y’为预测的值

注意reduce_sum的使用:

这里写图片描述
图片来源:知乎

reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1])) 
所以此语句的意思是将每一个样本的损失加起来,然后在用reduce_mean()求平均.因为y,y’都为1*10的向量,这是要注意的.

接下来就是要定义训练的方式,采用梯度下降,来最小话交叉熵. 
tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.InteractiveSession()#real datax = tf.placeholder(tf.float32,[None,784])y_ = tf.placeholder(tf.float32,[None,10])W = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))#predicty = tf.nn.softmax(tf.matmul(x,W)+b)#loss cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))#train waystrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

进行训练

##重点,全局参数初始化tf.global_variables_initializer().run()  ##迭代1000次,每次取出100个样本进行训练SGDfor i in range(1000):    batch_x,batch_y = mnist.train.next_batch(100)    train_step.run({x:batch_x,y_:batch_y})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

train_step.run({x:batch_x,y_:batch_y})这种方式为在运行的时候,feed_dict给x,y_的值,其中x为训练样本,y_为对应的真值.

评估

#testcorrect_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_meanprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels})
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

最终的结果为:0.9174

实现多层神经网络

为了方便的添加层,写一个添加层的函数,其中in_size,out_size都为神经元的尺度,input为上一层的输出,output为这一层的输出.

完整代码如下:

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/",one_hot=True)sess = tf.InteractiveSession()#定义添加隐含层的函数def add_layer(inputs, in_size, out_size,keep_prob=1.0,activation_function=None):    Weights = tf.Variable(tf.truncated_normal([in_size,out_size],stddev=0.1))    biases = tf.Variable(tf.zeros([out_size]))    Wx_plus_b = tf.matmul(inputs, Weights) + biases    if activation_function is None:        outputs = Wx_plus_b    else:        outputs = activation_function(Wx_plus_b)        outputs = tf.nn.dropout(outputs,keep_prob)  #随机失活    return outputs# holder变量x = tf.placeholder(tf.float32,[None,784])y_ = tf.placeholder(tf.float32,[None,10])keep_prob = tf.placeholder(tf.float32)     # 概率h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)##输出层w = tf.Variable(tf.zeros([300,10]))     #300*10b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(h1,w)+b)#定义loss,optimizercross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))train_step  =tf.train.AdagradOptimizer(0.35).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))       #高维度的acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    #要用reduce_meantf.global_variables_initializer().run()for i in range(3000):    batch_x,batch_y  = mnist.train.next_batch(100)    train_step.run({x:batch_x,y_:batch_y,keep_prob:0.75})    if i%1000==0:        train_accuracy = acuracy.eval({x:batch_x,y_:batch_y,keep_prob:1.0})        print("step %d,train_accuracy %g"%(i,train_accuracy))###########testprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

运行上述程序,得到正确为:0.9784,而这仅仅是加了一个隐含层而已. 
上面的隐含层的节点加的是300个神经元,如果要再加上一层400个神经元的非常的简单.

h1 = add_layer(x,784,300,keep_prob,tf.nn.relu)h2 = add_layer(h1,300,400,keep_prob,tf.nn.relu)##输出层w = tf.Variable(tf.zeros([400,10]))     #300*10b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(h2,w)+b)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看到,你可以随意的添加隐含的节点,和节点的个数,需要注意的是,维度不要搞错就行了.