cnn实现手写数字识别 mnist

本文介绍使用卷积神经网络(CNN)进行MNIST手写数字识别的全过程,包括数据加载、输入定义、卷积层与池化层构建、全连接层与softmax输出、损失函数设置及梯度下降优化器训练,最后展示模型准确率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#cnn : 1 卷积
# ABC 
# A: 激励函数+矩阵 乘法加法
# A CNN :  pool(激励函数+矩阵 卷积 加法)
# C:激励函数+矩阵 乘法加法(A-》B)
# C:激励函数+矩阵 乘法加法(A-》B) + softmax(矩阵 乘法加法)
# loss:tf.reduce_mean(tf.square(y-layer2))
# loss:code
#1 import 
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
# 2 load data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)
# 3 input
imageInput = tf.placeholder(tf.float32,[None,784]) # 28*28 
labeInput = tf.placeholder(tf.float32,[None,10]) # knn
# 4 data reshape
# [None,784]->M*28*28*1  2D->4D  28*28 wh 1 channel 
imageInputReshape = tf.reshape(imageInput,[-1,28,28,1])
# 5 卷积 w0 : 卷积内核 5*5 out:32  in:1 
w0 = tf.Variable(tf.truncated_normal([5,5,1,32],stddev = 0.1)) #stddev 是期望方差
b0 = tf.Variable(tf.constant(0.1,shape=[32]))
# 6 # layer1:激励函数+卷积运算
# imageInputReshape : M*28*28*1  w0:5,5,1,32  
layer1 = tf.nn.relu(tf.nn.conv2d(imageInputReshape,w0,strides=[1,1,1,1],padding='SAME')+b0)
# M*28*28*32
# pool 采样 数据量减少很多M*28*28*32 => M*7*7*32
layer1_pool = tf.nn.max_pool(layer1,ksize=[1,4,4,1],strides=[1,4,4,1],padding='SAME')
# [1 2 3 4]->[4]
# 7 layer2 out : 激励函数+乘加运算:  softmax(激励函数 + 乘加运算) #全连接层?
# [7*7*32,1024]
w1 = tf.Variable(tf.truncated_normal([7*7*32,1024],stddev=0.1))
b1 = tf.Variable(tf.constant(0.1,shape=[1024]))
h_reshape = tf.reshape(layer1_pool,[-1,7*7*32])# M*7*7*32 -> N*N1
# [N*7*7*32]  [7*7*32,1024] = N*1024
h1 = tf.nn.relu(tf.matmul(h_reshape,w1)+b1)
# 7.1 softMax
w2 = tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))
b2 = tf.Variable(tf.constant(0.1,shape=[10]))
pred = tf.nn.softmax(tf.matmul(h1,w2)+b2)# N*1024  1024*10 = N*10
# N*10( 概率 )N1【0.1 0.2 0.4 0.1 0.2 。。。】
# label。        【0 0 0 0 1 0 0 0.。。】
loss0 = labeInput*tf.log(pred)
loss1 = 0
# 7.2 
for m in range(0,500):#  test 100 #m=500
    for n in range(0,10):
        loss1 = loss1 - loss0[m,n]
loss = loss1/500

# 8 train
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
# 9 run
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        images,labels = mnist.train.next_batch(500) #m=500
        sess.run(train,feed_dict={imageInput:images,labeInput:labels})
        
        pred_test = sess.run(pred,feed_dict={imageInput:mnist.test.images,labeInput:labels})
        acc = tf.equal(tf.arg_max(pred_test,1),tf.arg_max(mnist.test.labels,1))
        acc_float = tf.reduce_mean(tf.cast(acc,tf.float32))
        acc_result = sess.run(acc_float,feed_dict={imageInput:mnist.test.images,labeInput:mnist.test.labels})
        print(acc_result)
        
        
        
        
以下是使用CNN实现手写数字识别MNIST的步骤: 1.导入必要的库和数据集 ```python import numpy as np import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras import backend as K # 加载MNIST数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() ``` 2.数据预处理 ```python # 将输入数据转换为CNN所需的格式 img_rows, img_cols = 28, 28 if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) # 将输入数据转换为浮点数并归一化 x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # 将标签转换为独热编码 num_classes = 10 y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) ``` 3.构建CNN模型 ```python model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) ``` 4.编译和训练模型 ```python model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) batch_size = 128 epochs = 12 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) ``` 5.评估模型 ```python score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值