Python代码实现CNN手写数字识别——MNIST数据集

注释很详细,这里不再赘述。 

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.examples.tutorials.mnist import input_data  # 下载数据集

# 初始化参数
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    # shape是必选项,输出张量维度,stddev=0.1用于设置正态分布被截断前的标准差
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    # 开始时设置为0.1
    return tf.Variable(initial)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    # ksize为卷积核大小  padding取valid时卷积之后图像大小为N=(imgSize-ksize)/strides
    # x 表示输入图像,要求是一个tensor具有[batch,in_height,in_width,in_channels]这样的shape,为float32或者64
    # 过滤器要求是一个tensor,具有[filter_height,filter_width,in_channels,out_channels]这样的shape

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

# tf.name_scope()和tf.variable_scope()是两个作用域,
# 一般与两个创建/调用变量的函数tf.variable() 和tf.get_variable()搭配使用,用于变量共享
# input image:pixel 28*28 = 784
with tf.name_scope('input'):
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder('float', [None, 10])  # y_ 代表真实结果
    # 创建占位符是 tf 读取数据的一种方法,让python代码来提供数据

with tf.name_scope('image'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])  # -1表示由实际情况来定,图像数目*宽*高/28/28/1=第一维数
    tf.summary.image('input_image', x_image, 8)
    # 输出带图像的probuf,汇总数据的图像的的形式如下: ’ tag /image/0’, ’ tag /image/1’…,如:input/image/0等

# 第一个卷积层
with tf.name_scope('conv_layer1'):
    W_conv1 = weight_variable([5, 5, 1, 32])  # 卷积核(kernel): 5*5*1, kernel个数: 32
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 输出(output): 28*28*32
# 池化
with tf.name_scope('pooling_layer'):
    h_pool1 = max_pool_2x2(h_conv1)  # 最大池化, 输出(output): 14*14*32

# 第二个卷积层
with tf.name_scope('conv_layer2'):
    W_conv2 = weight_variable([5, 5, 32, 64])  # 卷积核(kernel): 5*5, 深度: 32, kernel个数: 64
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  # 输出(output): 14*14*64
# 池化
with tf.name_scope('pooling_layer'):
    h_pool2 = max_pool_2x2(h_conv2)  # 最大池化, 输出(output): 7*7*64


# 第一个全连接层
with tf.name_scope('fc_layer3'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])  # 大小 : 1*1024
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  # 输出(output): 1*1024

# dropout层  dropout层一般加在全连接层 防止过拟合,提升模型泛化能力
with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)


# 第二个全连接层
# 训练模型 : y = softmax(x * w + b)
with tf.name_scope('output_fc_layer4'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])  # 大小 : 1*10

with tf.name_scope('softmax'):
    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  # 输出(output): 1*10

with tf.name_scope('lost'):
    cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))   # 交叉熵计算损失函数
    tf.summary.scalar('lost', cross_entropy)

with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    # AdamOptimizer是tensorflow中的一种优化器,1e-4是学习率
    # 为了最小化损失函数,需要用到反向传播思想,随机梯度下降算法来最小化损失函数

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    tf.summary.scalar('accuracy', accuracy)  # 显示标量信息
    '''
    tf.argmax(y_conv, 1) 是返回第二维(行方向)上最大值的索引,
    tf.equal() 是比较两个值是否相等,返回一个 bool 值(True or False),
    tf.cast() 是将bool 值转换为 1.0 or 0.0 的浮点类型,
    tf.reduce_mean() 是计算平均值。
    '''

merged = tf.summary.merge_all()
train_summary = tf.summary.FileWriter(r'C:\Users\12956\Anaconda3\Lib\site-packages', tf.get_default_graph())
# 将这里的地址路径改成tensorboard文件夹的绝对路径地址

init = tf.global_variables_initializer()
# 进行初始化,之前只是定义variable

# 执行
with tf.Session() as sess:
    sess.run(init)
    # 构建一个session,在session中运行
    # 训练数据 : 得到参数 w 和 b
    for i in range(2000):  # 迭代2000次
        batch = mnist.train.next_batch(50)
        # 批量给网络提供数据

        result, _ = sess.run([merged, train_step], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
        # 在mnist数据集中,0是输入的图片,1是输入的标签,这个batch是784*10的
        # train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

        if i % 100 == 0:
            # train_accuracy = sess.run(accuracy, feed_dict)
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})  # 无dropout
            print('step %d, training accuracy %g' % (i, train_accuracy))

            # result = sess.run(merged, feed_dict={x: batch[0], y_: batch[1]})
            train_summary.add_summary(result, i)

    train_summary.close()

    print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))


可以直接复制运行,记得将路径改一下~

#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
#from tensorflow.examples.tutorials.mnist import input_data
#用下面这几句代码来代替上面这句
#import tensorflow as tf

tf.__version__
mint = tf.keras.datasets.mnist
(x_, y_), (x_1, y_1) = mint.load_data()
import matplotlib.pyplot as plt
plt.imshow(x_[0], cmap="binary")
plt.show()

import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# import tensorflow as tf
# (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets ( ” MNIST_data/ ”, one_hot=True)

# import tensorflow.examples.tutorials.mnist.input_data as input_data
# mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# 初始化权重函数
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1);  # 生成维度是shape标准差是0.1的正态分布数
    return tf.Variable(initial)


# 初始化偏置项
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)  # 生成维度为shape的全为0.1的向量
    return tf.Variable(initial)


# 定义卷积函数
def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
    # strides: 卷积时在图像每一维的步长,这是一个一维的向量,
    # [ 1, strides, strides, 1],第一位和最后一位固定必须是1
    # padding参数是string类型,值为“SAME” 和 “VALID”,表示的是卷积的形式。
    # 设置为"SAME"时,会在原图像边缘外增加几圈0来使卷积后的矩阵和原图像矩阵的维度相同
    # 设置为"VALID"则不考虑这一点,卷积后的矩阵维度会相应减少,例如原图像如果是5*5,卷积核是3*3
    # 那么卷积过后的输出矩阵回是3*3的


# 定义一个2*2的最大池化层
def max_pool_2_2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    # 第一个参数value:需要池化的输入,一般池化层接在卷积层后面,
    # 依然是[batch, height, width, channels]这样的shape
    # 第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],
    # 因为我们不想在batch和channels上做池化,所以这两个维度设为了1
    # 第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,
    # 一般也是[1, stride,stride, 1]
    # 第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'


if __name__ == "__main__":
    # 定义输入变量
    x = tf.placeholder("float", shape=[None, 784])  # 占位
    # 浮点型变量,行数不定,列数为784(每个图像是一个长度为784(28*28)的向量)

    # 定义输出变量
    y_ = tf.placeholder("float", shape=[None, 10])  # 占位
    # 浮点型变量,行数不定,列数为10,输出一个长度为10的向量来表示每个数字的可能性
    # 初始化权重,第一层卷积,32的意思代表的是输出32个通道
    # 其实,也就是设置32个卷积,每一个卷积都会对图像进行卷积操作

    w_conv1 = weight_variable([5, 5, 1, 32])  # 生成了32个5*5的矩阵
    # 初始化偏置项
    b_conv1 = bias_variable([32])

    x_image = tf.reshape(x, [-1, 28, 28, 1])
    # 将输入的x转成一个4D向量,第2、3维对应图片的宽高,最后一维代表图片的颜色通道数
    # 输入的图像为灰度图,所以通道数为1,如果是RGB图,通道数为3
    # tf.reshape(x,[-1,28,28,1])的意思是将x自动转换成28*28*1的数组
    # -1的意思是代表不知道x的shape,它会按照后面的设置进行转换

    # 卷积并激活
    h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
    # 池化
    h_pool1 = max_pool_2_2(h_conv1)
    # 第二层卷积
    # 初始权重
    w_conv2 = weight_variable([5, 5, 32, 64])
    # 在32个第一层卷积层上每个再用一个5*5的卷积核在做特征提取,并输出到第二层卷积层,
    # 第二层设置了64个卷积层

    # 初始化偏置项
    b_conv2 = bias_variable([64])
    # 将第一层卷积池化后的结果作为第二层卷积的输入加权求和后激活
    h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
    # 池化
    h_pool2 = max_pool_2_2(h_conv2)
    # 设置全连接层的权重
    w_fc1 = weight_variable([7 * 7 * 64, 1024])
    # 28*28的原图像经过两次池化后变为7*7,设置了1024个输出单元

    # 设置全连接层的偏置
    b_fc1 = bias_variable([1024])
    # 将第二层卷积池化后的结果,转成一个7*7*64的数组
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    # 通过全连接之后并激活
    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)
    # 设置每个单元保留的概率来随机放弃一些单元来防止过拟合

    # 输出层
    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)

    # 日志输出,每迭代100次输出一次日志
    # 定义交叉熵为损失函数
    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())
    # 上面的两行是在为tf的输出变量做准备
    # 下载minist的手写数字的数据集
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    for i in range(20000):  # 迭代20000次
        batch = mnist.train.next_batch(50)  # 设置batch,即每次用来训练模型的数据个数
        if i % 100 == 0:  # 每100次迭代输出一次精度
            train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            # 给之前占位的x和y_本次训练的batch个数据中第一个数据的图像矩阵和标签,不考虑过拟合
            # 计算当前的精度

            print("step %d,training accuracy %g" % (i, train_accuracy))
        train_step.run(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
        # 当i不能被100整除时的训练过程,考虑过拟合,单元保留的概率为0.5

    print("test accuracy %g" % accuracy.eval(session=sess, feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
    # 输出测试集的精度

 两种代码实现的功能一样,只是写法不同,第一种是使用with方法编写的,第二种是C语言思想编写的,先定义函数,再使用。

学无止境,一起学习~

猜你喜欢

转载自blog.csdn.net/baidu_41774120/article/details/117622234