mnist 识别

本文介绍了一种使用卷积神经网络(CNN)进行手写数字识别的方法。通过两层卷积层和池化操作,结合全连接层进行分类预测,实现了MNIST数据集的手写数字识别任务,并详细展示了模型构建过程及训练细节。
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os



def crete_weights(shape):
    # return tf.Variable(initial_value=tf.random_normal(shape=shape))
    return tf.Variable(initial_value=tf.random_normal(shape=shape, stddev = 0.01))# 初始化权重的 标准差

def crete_model(x):
    """
    构建卷积神经网络
    :return:
    """
    # 1 第一个卷积层
    with tf.variable_scope("conv1"):
        # 卷积层
        # 将x[None, 784]进行形状上的修改
        input_x = tf.reshape(x, shape = [-1, 28,28,1])
        # 定义32 个filter和偏置
        conv1_weights = crete_weights(shape=[5,5,1,32])
        conv1_bias = crete_weights(shape=[32])
        conv1_x = tf.nn.conv2d(input=input_x, filter=conv1_weights, strides=[1,1,1,1], padding="SAME") + conv1_bias
        # 激活层
        relu1_x = tf.nn.relu(conv1_x)

        # 池化层
        pool1_x = tf.nn.max_pool(value=relu1_x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")
    # 1 第2个卷积层
    with tf.variable_scope("conv2"):
        # 卷积层
        # 定义32 个filter和偏置
        conv2_weights = crete_weights(shape=[5, 5, 32, 64])
        conv2_bias = crete_weights(shape=[64])
        conv2_x = tf.nn.conv2d(input=pool1_x, filter=conv2_weights, strides=[1, 1, 1, 1],
                               padding="SAME") + conv2_bias
        # 激活层
        relu2_x = tf.nn.relu(conv2_x)

        # 池化层
        pool2_x = tf.nn.max_pool(value=relu2_x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
    # 全连接层
    with tf.variable_scope("full_connection"):
        x_fc = tf.reshape(pool2_x, shape=[-1,7*7*64])
        weights_fc = crete_weights(shape=[7*7*64,10])
        bias_fc = crete_weights(shape=[10])
        y_predict = tf.matmul(x_fc, weights_fc) + bias_fc
    # 调参  设置学习率  修改初始化权重的值 batch_normalization   dropout(防止过拟合)
    return y_predict

def full_connection():
    """
    用全连接对手写是数字进行识别
    :return:
    """
    # 1 准备数据
    mnist = input_data.read_data_sets('mnist_data', one_hot=True)
    with tf.variable_scope("mnist_data"):
        x  = tf.placeholder(dtype=tf.float32, shape=(None,784))
        y_true = tf.placeholder(dtype=tf.float32, shape=(None, 10))

    # with tf.variable_scope("fc_model"):
    #     weights  = tf.Variable(initial_value=tf.random_normal(shape=[784,10]))
    #     bias = tf.Variable(initial_value=tf.random_normal(shape=[10]))
    #     y_predict  = tf.matmul(x,weights) + bias
    y_predict = crete_model(x)
    # 第一个卷积大层:
    # 卷积层 32 filter
    # 激活层 relu
    # 赤化   大小 2 步长2
    # 第二同第一
    # 输入形状 [None, 28,28,1]
    # weights = tf.Variable(initial_value=tf.random_normal(shape=[5,5,1,32]))
    # bias = tf.Variable(initial_value=tf.random_normal(shape=[32]))
    # initial_value = random_normal(shape = [F,F,3,32])
    # 输出形状  [None, 28,28,32]
    # 3构造损失函数
    error = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))
    # 4 优化损失
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)# 一般是最多的
    # optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)

    # 5 准确率计算
    equal_list  = tf.equal(tf.argmax(y_true, 1),
                            tf.argmax(y_predict,1))# 返回的是bool型
    accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
    # 初始化变量
    init = tf.global_variables_initializer()
    # 开启会话
    with tf.Session() as sess:
        sess.run(init)
        image, label = mnist.train.next_batch(100)
        print("训练之前,损失为:%f" % sess.run(error, feed_dict={x:image, y_true:label}))
        # 开始训练
        for i in range(500):
            _, loss, accuracy_value  = sess.run([optimizer, error, accuracy], feed_dict={x:image, y_true:label})
            print("第%d次训练的损失为%f, 准确率为% f" %(i+1, loss, accuracy_value))
    return  None
# 准确率  比较输出的结果最大值与真实值最大值所在的位置
    # print(mnist.train.next_batch(1))
    # print(mnist.train.images[0])  # 查看特征值
    # print(mnist.train.labels[0])  # 目标值
    # one - hot  0 1 ...9

if __name__ == "__main__":
    full_connection()
    # crete_model()

多层感知机(MLP)也叫人工神经网络(ANN),除输入输出层外,中间可以有多个隐层,最简单的MLP只含一个隐层,即三层结构 [^2]。基于MNIST数据集,可建立MLP模型,实现0 - 9数字的十分类任务 [^3]。 ### 方法 1. **数据加载**:从`keras.datasets`中加载MNIST数据 [^3]。 2. **数据预处理**:包括图像数据维度转换与归一化、输出结果格式转换 [^3]。 3. **模型构建**:构建具有两层隐藏层,每层有392个神经元的模型 [^3]。 4. **模型训练与评估**:计算模型在预测数据集的准确率 [^3]。 ### 代码示例 ```python # 加载mnist数据 from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() # 后续还需要进行数据预处理、模型构建、训练和评估等步骤 # 以下是一个简化的示例框架,实际应用中需要根据需求完善 # 数据预处理 # 图像数据维度转换与归一化 X_train = X_train.reshape(-1, 28 * 28).astype('float32') / 255 X_test = X_test.reshape(-1, 28 * 28).astype('float32') / 255 # 输出结果格式转换 from keras.utils import to_categorical y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) # 构建模型 from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(392, activation='relu', input_shape=(28 * 28,))) model.add(Dense(392, activation='relu')) model.add(Dense(10, activation='softmax')) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test)) # 评估模型 loss, accuracy = model.evaluate(X_test, y_test) print(f"Test Loss: {loss}, Test Accuracy: {accuracy}") ``` ### 相关资料 在【深度学习】Keras MNIST手写识别(一)中,对整个运行环境、为什么用Keras、如何进行学习、深度神经网络框架等做了大体介绍,并且代码简单且已经过验证 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值