卷积神经网络手写体训练代码实现--基于python tensorflow

一、介绍
输入为28x28的图片的浮点型数据
输出0-9的概率值

二、代码

#导入库
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#产生权重参数变量
def w_value(shape):
    w_v = tf.truncated_normal(shape, stddev=0.1)#生成张量产生随机数填充
    return tf.Variable(w_v)#返回变量张量,填充随机数

#产生偏置参数变量
def b_value(shape):
    b_v = tf.constant(0.1, shape=shape)
    return tf.Variable(b_v)

#卷积计算
def conv_2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

#池化计算
def max_pool_(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])#输入图片
y_ = tf.placeholder(tf.float32, [None, 10])#标签
keep_prob = tf.placeholder(tf.float32)

x_4d = tf.reshape(x, [-1, 28, 28, 1])#转换图片为4阶张量
#计算图
'''
//输入
//图片28x28 单通道
//第一层卷积核 w 5x5x32    b 32
//第二层卷积核 w 5x5x32x64 b 64
//第一层全连接 w 1024x512  b 512
//第二层全连接 w 512x10  b 10 
//返回 识别结果
'''
#下载数据集
print("下载数据集...")
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#前向传播
#第一层卷积 输入 28x28 输出28-5+1+2 = 26
print("第一层卷积...")
conv_w1 = w_value([5, 5, 1, 32])#w1[5][5][1][32]
conv_b1 = b_value([32])
conv1_out = tf.nn.relu(conv_2d(x_4d, conv_w1) + conv_b1)
#池化 输入26x26x32 输出14x14x32
print("第一层池化...")
pool1_out = max_pool_(conv1_out)

#第二层卷积 输入14x14x32 输出14-5+1+2 = 12
print("第二层卷积...")
conv_w2 = w_value([5, 5, 32, 64])#w2[5][5][32][64]
conv_b2 = b_value([64])
conv2_out = tf.nn.relu(conv_2d(pool1_out, conv_w2) + conv_b2)
#池化 输入12x12x64 输出(12+2)/2 = 7
print("第二层池化...")
pool2_out = max_pool_(conv2_out)

#转换矩阵
pool2_sw_out = tf.reshape(pool2_out, [-1, 7 * 7 * 64])

#第一层全连接 输入7x7x64
print("第一层全连接...")
fc_w1 = w_value([7*7*64, 1024])
fc_b1 = b_value([1024])
fc1_out = tf.nn.relu(tf.matmul(pool2_sw_out,fc_w1) + fc_b1)

#第二层全连接
print("第二层全连接...")
fc_w2 = w_value([1024, 10])
fc_b2 = b_value([10])
fc2_out = tf.matmul(fc1_out,fc_w2) + fc_b2
#反向传播
#计算损失值
loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=fc2_out))
#梯度下降
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)

#识别准确率的计算
correct_prediction = tf.equal(tf.argmax(fc2_out, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

#初始化参数
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

#循环导入数据到神经网络
for i in range(500):
    batch = mnist.train.next_batch(50)#读取训练图片和标签
    train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob: 0.5})#启动训练
    if(i % 100 == 0):
        train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0})
        print("step",i)
        print("识别率%g"%train_accuracy)
        
#打印训练结果,传入测试集图片,识别率
print("测试识别正确率%g"%accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
#训练结束

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值