利用CNN实现手写体识别

来源:互联网 发布:linux 电池管理 编辑:程序博客网 时间:2024/06/11 13:27

用TensorFlow实现CNN代码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
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81

#!/usr/bin/env python# -*- coding:utf-8 -*-__author__ = 'houlisha'import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)# 产生随机变量,符合 normal 分布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)# 定义2维的convolutional图层# strides:每跨多少步抽取信息,strides[1, x_movement,y_movement, 1], [0]和strides[3]必须为1# padding:边距处理,“SAME”表示输出图层和输入图层大小保持不变,设置为“VALID”时表示舍弃多余边距(丢失信息)def conv2d(x, W):    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')# 定义pooling图层# pooling:解决跨步大时可能丢失一些信息的问题,max-pooling就是在前图层上依次不重合采样2*2的窗口最大值def max_pool_2x2(x):    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')x = tf.placeholder(tf.float32, [None, 784])x_image = tf.reshape(x, [-1, 28, 28, 1])                   # 将原图reshape为4维,-1表示数据个数,28*28=784,1表示颜色通道数目y_ = tf.placeholder(tf.float32, [None, 10])### 1. 第一层网络# 把x_image的厚度由1增加到32,长宽由28*28缩小为14*14W_conv1 = weight_variable([5, 5, 1, 32])                    # 按照[5,5,输入通道=1,输出通道=32]生成一组随机变量b_conv1 = bias_variable([32])                               h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)    # 输出size 28*28*32(因为conv2d()中x和y步长都为1,边距保持不变)h_pool1 = max_pool_2x2(h_conv1)                             # 输出size 14*14*32### 2. 第二层网络# 把h_pool1的厚度由32增加到64,长宽由14*14缩小为7*7W_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)### 3. 第一层全连接# 把h_pool2由7*7*64,变成1024*1W_fc1 = weight_variable([7*7*64, 1024])b_fc1 = bias_variable([1024])h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])               # 把pooling后的结构reshape为一维向量h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)keep_prob = tf.placeholder('float')h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                   # 按照keep_prob的概率扔掉一些,为了减少过拟合 ### 4. 第二层全连接使用softmax计算概率进行分类, 最后一层网络,1024 -> 10, 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 = -tf.reduce_sum(y_ * tf.log(y_conv))train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))sess = tf.Session()sess.run(tf.initialize_all_variables())for i in range(20000):    batch = mnist.train.next_batch(50)    if i % 100 == 0:        train_accuracy = accuracy.eval(session = sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})        print 'step %d, training accuracy %g' % (i, train_accuracy)    sess.run(train_step, feed_dict = {x: batch[0], y_: batch[1], keep_prob: 0.5})print 'test accuracy %g' % accuracy.eval(session = sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})


tf.nn.conv2d到底做了啥?

参考:http://stackoverflow.com/questions/34619177/what-does-tf-nn-conv2d-do-in-tensorflow

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)

  • input: A Tensor. type必须是以下几种类型之一: half, float32, float64.
  • filter: A Tensor. type和input必须相同
  • strides: A list of ints.一维,长度4, 在input上切片采样时,每个方向上的滑窗步长,必须和format指定的维度同阶
  • padding: A string from: “SAME”, “VALID”. padding 算法的类型
  • use_cudnn_on_gpu: An optional bool. Defaults to True.
  • data_format: An optional string from: “NHWC”, “NCHW”, 默认为”NHWC”。 
    指定输入输出数据格式,默认格式为”NHWC”, 数据按这样的顺序存储: 
    [batch, in_height, in_width, in_channels] 
    也可以用这种方式:”NCHW”, 数据按这样的顺序存储: 
    [batch, in_channels, in_height, in_width]
  • name: 操作名,可选.

conv2d实际上执行了以下操作:

  1. Flattens the filter to a 2-D matrix with shape 
    [filter_height * filter_width * in_channels, output_channels]
  2. Extracts image patches from the the input tensor to form a virtual tensor of shape 
    [batch, out_height, out_width, filter_height * filter_width * in_channels]
  3. For each patch, right-multiplies the filter matrix and the image patch vector.
    来源: http://blog.csdn.net/pirage/article/details/53187483
原创粉丝点击