CNN-MNIST手写体识别

import tensorflow as tf
import random
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np

#设置随机种子
tf.set_random_seed(777)
#获取数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#设置参数
learning_rate = 0.001
training_epochs = 15
batch_size = 100

#定义占位符
x = tf.placeholder(tf.float32,shape=[None,784])
x_img = tf.reshape(x,shape=[-1,28,28,1])
y = tf.placeholder(tf.float32,shape=[None,10])

#第一层卷积,输入图片是(?,28,28,1)
w1 = tf.Variable(tf.random_normal([3,3,1,32]))
L1 = tf.nn.conv2d(x_img,w1,strides=[1,1,1,1],padding="SAME") #(?,28,28,32)
L1 = tf.nn.relu(L1)
#池化
L1 = tf.nn.max_pool(L1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME") #(?,14,14,32)

#第二层卷积
w2 = tf.Variable(tf.random_normal([3,3,32,64]))
L2 = tf.nn.conv2d(L1,w2,strides=[1,1,1,1],padding="SAME") #生成(?,14,14,64)
L2 = tf.nn.relu(L2)
#池化
L2 = tf.nn.max_pool(L2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")#生成(?,7,7,64)

#全连接层 
L2_flat = tf.reshape(L2,shape=[-1,7*7*64])

#全连接7*7*64 input 》output

w3 = tf.Variable(tf.random_normal([7*7*64,10]))
b = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(L2_flat,w3)+b

#代价或损失函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y))

#优化器
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

#定义会话
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print("开始学习")
for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples/batch_size)
    for i in range(total_batch):
        batch_xs,batch_ys = mnist.train.next_batch(batch_size)
        cost_val,_ = sess.run([cost,optimizer],feed_dict={x:batch_xs,y:batch_ys})
        avg_cost += cost_val/total_batch
    print(epoch,avg_cost)

print("学习完成")

#精确度
correct_pre = tf.equal(tf.argmax(logits,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))

print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))
#关闭会话
sess.close()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值