tensorflow实现手写体识别的两种方法

一、softmax

参考博文'Tensorflow 实现 MNIST 手写数字识别'http://blog.csdn.net/u010858605/article/details/69830657

# coding=utf-8
#!/usr/bin/env python

import tensorflow as tf

# 获取数据,MNIST数据集包含55000样本的训练集,5000样本的验证集,10000样本的测试集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("input_data", one_hot=True)

# 显示图像和类标的形状
print('训练集信息:')
print(mnist.train.images.shape,mnist.train.labels.shape)
print('测试集信息:')
print(mnist.test.images.shape,mnist.test.labels.shape)
print('验证集信息:')
print(mnist.validation.images.shape,mnist.validation.labels.shape)

# 实现模型 y=softmax(wx+b)
# placeholder:输入数据的地方,None 代表不限条数的输入,每条是784维的向量
# Variable:存储模型参数,持久化的
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b)

# 定义一个交叉熵作为loss函数cross_entropy,其中y是我们预测的概率分布, y_是实际的分布
y_ = tf.placeholder(tf.float32, [None,10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

# 采用随机梯度下降法,步长为0.5进行训练
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 让模型循环训练1000次,每次随机train100条样本
tf.global_variables_initializer().run()
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  train_step.run({x: batch_xs, y_: batch_ys})

# 模型评估
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('MNIST手写图片准确率:')
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

实现的流程:

  1. 定义算法公式,也就是神经网络前向传播时的计算。
  2. 定义 loss ,选定优化器,并指定优化器优化 loss。
  3. 迭代地对数据进行训练。
  4. 在测试集或验证集上对准确率进行评测。
运行结果如下:

二、CNN

参考博文'用TensorFlow构造CNN进行手写数字识别' http://blog.csdn.net/clcwcxfwf/article/details/72854204

‘TensorFlow学习笔记(3)----CNN识别MNIST手写数字’http://blog.csdn.net/PhDat101/article/details/52403127

构建两层的卷积神经网络来进行手写数字的识别,数据集是MNIST,开发平台是TensorFlow。

网络的结构为:
input layer => convolutional layer => pooling layer => convolutional layer => pooling layer => fully connected layer => fully connected layer

# coding=utf-8
# !/usr/bin/env python

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf


# 用于构建2层的卷积神经网络
def deepnn(x):
    # 把图像向量还原成28*28的图像
    x_image = tf.reshape(x, [-1, 28, 28, 1])

    # 第一层卷积
    # [卷积核的高度,卷积核的宽度,RGB通道数量,输出的通道数量]
    W_conv1 = weight_variable([5, 5, 1, 32])
    # bias变量,长度为32的向量
    b_conv1 = bias_variable([32])

    # relu函数,即f(x)=max(0,x)
    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)

    # 全连接层,共1024个神经元
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])

    # dropout是将某一些神经元的输出变为0,这是为了防止过拟合
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # softmax层
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

    return y_conv, keep_prob


# 卷积函数,待操作的数据x,模板W,tensor不同维度上的步长,强制与原tensor等大
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


# pooling函数,平面数据的pool模板2*2,平面数据滑动步长2*2(非重叠的pool)
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


# 用于分配系数
def weight_variable(shape):
    # 均值0标准方差0.1,剔除2倍标准方差之外的随机数据
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


# 用于分配偏置
def bias_variable(shape):
    # 统一值0.1
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


# 读取数据
mnist = input_data.read_data_sets('input_data', one_hot=True)

# 定义图片和标签的占位符
# x是输入的图像,y_是对应的标签
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

y_conv, keep_prob = deepnn(x)

# 用交叉熵来计算loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
# AdamOptimizer调参
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, tf.float32))

with tf.Session() as sess:
    # 初始化
    sess.run(tf.global_variables_initializer())
    # 开始训练
    for i in range(20000):
        # 每次50张图片
        batch = mnist.train.next_batch(50)
        # 每100次迭代输出一次日志
        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))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

        # 验证最终的准确率
    print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_:mnist.test.labels,keep_prob:1.0}))
实现的流程:
  1. 构建卷积网络
  2. 定义 loss ,选定优化器,并指定优化器优化 loss。
  3. 迭代地对数据进行训练。
  4. 在测试集或验证集上对准确率进行评测。


  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值