TensorFlow实现Lenet-5

来源:互联网 发布:iphone文件传输软件 编辑:程序博客网 时间:2024/05/18 03:05
'''载入MNIST数据集,并创建默认的Interactive Session'''import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot = True)sess = tf.InteractiveSession()'''创建卷及神经网络的权重和偏置tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准
差。这个函数产生正太分布,均值和标准差自己设定。这是一个截断的产生正太分布的函数,就是说产生
正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成。Variable() 构造器需要一个初始值,可以是任意类型和shape 的Tensor。初始值定义了变量的type和
shape。构造完成之后,变量的type和shape是固定的。可以使用assign 方法来修改变量的值。'''def weight_variable(shape):        initial = tf.truncated_normal(shape, stddev=0.1)        return tf.Variable(initial)def bias_variable(shape):        initial = tf.constant(0.1, shape = shape)        return tf.Variable(initial)'''tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有
[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量,
 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true结果返回一个Tensor,这个输出,就是我们常说的feature map'''def conv2d(x, W):        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')"""tf.nn.max_pool(value, ksize, strides, padding, name=None)参数是四个,和卷积很类似:第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式"""def max_pool_2x2(x):        return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')'''定义placeholder,x是特征,y_是真实的label卷积神经网络会利用空间信息,因此需要将1D的输入向量x转化为2D图片结构x_image,即1*784转化成28*28,
tf.reshape(tensor,shape, name=None) 函数的作用是将tensor变换为参数shape的形式。 其中shape为一个列表形式,特殊的一点是列表中可以存在-1。-1代表的含义是不用我们自己指定这一维
的大小,函数会自动计算,但列表中只能存在一个-1。'''x = tf.placeholder(tf.float32, [None, 784])y_ = tf.placeholder(tf.float32, [None, 10])x_image = tf.reshape(x, [-1,28,28,1])'''定义第一个卷积层:'''W_conv1 = weight_variable([5,5,1,32])b_conv1 = bias_variable([32])h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)h_pool1 = max_pool_2x2(h_conv1)'''定义第二个卷积层:'''W_conv2 = weight_variable([5,5,32,64])b_conv2 = bias_variable([64])h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)h_pool2 = max_pool_2x2(h_conv2)'''定义一个全连接层,节点数为2014个:经历两次步长为2*2的最大池化,图片尺寸28*28变成7*7,由于第二层卷积核数量为64,输入尺寸即为7*7*64'''W_fc1 = weight_variable([7 * 7 * 64, 1024])b_fc1 = bias_variable([1024])h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)'''定义一个Dropout层:为了减轻过拟合,使用Dropout,通过一个placeholder传入keep_prob比率进行控制,在训练过程中,我们随
机丢弃一部分节点的数据来减轻过拟合,预测时则保留全部的数据来追求最好的预测性能.'''keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)'''最后将Dropout层的输出连接一个Softmax层,得到最后的概率输出'''W_fc2 = weight_variable([1024, 10])b_fc2 = bias_variable([10])y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)'''定义损失函数cross entropy, 优化器使用Adam, 并给予一个比较小的学习速率1e-4y_是标记所以是严格的01向量,y_conv表示的属于每一类的概率'''cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)'''定义评定准确率的操作:实例中y_conv与y_的大小是50*10,即保存这50个样本的分类结果与实际结果,如[0 0 0 0 1 0 0 0 0 0]
表示4,第5个元素不为0,(0,1,2,3,4)tf.argmax(),是求列表中最大值的下标,tf.argmax([0 0 0 0 1 0 0 0 0 0])=4tf.argmax([[0 0 0 0 1 0 0 0 0 0],[0 0 0 1 0 0 0 0 0 0]],1)=[4 3],1表示按照行找最大a = tf.equal([1,2],[3,4])输出[False False]tf.cast([False False])输出[ 0.  0.]'''correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))'''开始训练过程:(1)首先初始化所有参数(2)设置训练时的Dropout的keep_prob比率为0.5(3)然后使用大小为50的mini-batch,进行20000次的训练迭代,参与训练样本的数量总共为100万(4)其中每训练100次,对准确率进行一次评测(评测时keep_prob设为1),用于实时监控模型性能'''tf.global_variables_initializer().run()for i in range(20000):        batch = mnist.train.next_batch(50)# input:1024行*50列,label:50行*10列;        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})        print(batch[1])        if i%100 == 0:                train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_:batch[1],\
keep_prob: 1.0})                print ("step %d     , training accuracy %g"%(i, train_accuracy))'''在最终的数据集上进行全面测试,得到整体的分类的准确率'''print("test_accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, \
          y_: mnist.test.labels, keep_prob: 1.0}))
原创粉丝点击