python 简单使用MNIST数据集+卷积神经网络实现手写数字识别

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

#1 读取数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#2 建立模型  使用卷积神经网络

#2.1 输入图像与标签
x = tf.placeholder("float", shape = [None, 28,28,1])
y_ = tf.placeholder("float", shape = [None, 10]) 

#2.2 搭建卷积神经网络    卷积+卷积+池化+全连接

#2.2.1 卷积层 
w1 = tf.Variable(tf.truncated_normal([3, 3, 1, 32])) #高宽3*3 单通道 32个filter 
b1 = tf.Variable(tf.zeros([32]))                     #每个filter初始bias为0
conv1 = tf.nn.conv2d(input=x, filter=w1, strides=[1, 1, 1, 1], padding='SAME') + b1
conv1 = tf.nn.relu(conv1)                            #进行卷积 非线性激活

#2.2.2 卷积层
w2 = tf.Variable(tf.truncated_normal([3, 3, 32, 32])) #高宽3*3 32通道 32个filter 
b2 = tf.Variable(tf.zeros([32]))                      #每个filter初始bias为0
conv2 = tf.nn.conv2d(input=conv1, filter=w2, strides=[1, 1, 1, 1], padding='SAME') + b2
conv2 = tf.nn.relu(conv2)                             #进行卷积 非线性激活 

#2.2.3 池化
pool = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

#2.2.4 全连接
w = tf.Variable(tf.truncated_normal([14 * 14 * 32, 10], stddev=0.1))
b = tf.Variable(tf.zeros([10]))
pool_reshape = tf.reshape(pool, [-1, 14*14*32])

#2.2.5 输出
y = tf.matmul(pool_reshape, w) + b

#3 损失函数 优化训练
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y)
crossEntropyLoss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer().minimize(crossEntropyLoss)

#4 测试
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

#5 开启会话
with tf.Session() as sess:
    # 初始化
    sess.run(tf.global_variables_initializer())

    # 训练
    for i in range(501):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        batch_xs = batch_xs.reshape([100,28,28,1])
        sess.run(optimizer, feed_dict={x: batch_xs, y_: batch_ys})
        
        # 测试模型
        #if i%100 == 0:
            #result = sess.run(accuracy, feed_dict={x: mnist.test.images.reshape([10000,28,28,1]), y_: mnist.test.labels}) * 100
            #print(result)
    # 测试模型
    sum = 0;
    for i in range(10000):
        sum += sess.run(accuracy, feed_dict={x: mnist.test.images[i].reshape([1,28,28,1]), y_: mnist.test.labels[i].reshape([1,10])})
    print(sum)
    print(sum/10000)

 结果:       

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大米粥哥哥

感谢认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值