Tensorflow(五)使用CNN对MNIST数据集进行分类

在tensorflow(二)中对MNIST数据集进行分类使用单层神经网络,梯度下降法以0.2的学习因子迭代了100次取得了92%的准确率,这个网络很简单,使用较大的学习因子也不会出现梯度爆炸或者梯度消失的情况,但是在复杂些的网络,比如这里用到的三层CNN网络使用0.2的学习因子就过大了。

本文结合了tensorfow(三)中的卷积神经网络模型以及tensorflow(四)中的tensorboard查看方法,神经网共有三层,两个卷积层,一个全连接层,一般情况下对特征图进行卷积操作后也会进行池化操作,所以讲池化层也包含在卷积层当中,当然代码实现是分开的,只是计算神经网络的层次时将他们划分在一起,并且统称为一个卷积层。

具体的内容在前面两节中都有总结,这里就直接贴代码了,需要说明的地方会注释:

#导包
import numpy as np
import h5py
import tensorflow as tf

#MNIST数据
#需要注意的一点是,数据格式与单层神经网络不同,CNN不需要把数据整合为(m*n)的格式
#也就是CNN不需要将所有特征值都合并在一起
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)
train_x = mnist.train.images
train_y = mnist.train.labels

test_x = mnist.test.images
test_y = mnist.test.labels #(55000, 10)

train_x = train_x.reshape([-1,28,28,1]) #(55000, 28, 28, 1)
test_x = test_x.reshape([-1,28,28,1]) # (10000, 28, 28, 1)


#定义一个 变量所有summary的整合
def variable_summaries(var):
    with tf.name_scope('summaries'):
        mean = tf.reduce_mean(var)
        tf.summary.scalar('mean', mean)
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.summary.scalar('stddev', stddev)
        tf.summary.scalar('max', tf.reduce_max(var))
        tf.summary.scalar('min', tf.reduce_min(var))
        tf.summary.histogram('histogram', var)


#新建占位符
def create_placeholders(n_H0,n_W0,n_C0,n_y):
    with tf.name_scope('input'):
        X = tf.placeholder(shape=[None,n_H0,n_W0,n_C0],dtype = tf.float32,name='x_input')
        Y = tf.placeholder(shape=[None,n_y],dtype = tf.float32,name='y_input')
    return X,Y


#向前传播
def forward_propagation(X):
    tf.set_random_seed(1)
    
    #第一个卷积层 conv-relu-pooling
    with tf.name_scope(
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用CNN实现MNIST数据集分类的Python代码: ```python import tensorflow as tf from tensorflow.keras import datasets, layers, models # 加载MNIST数据集 (train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data() # 数据预处理 train_images = train_images.reshape((-1, 28, 28, 1)) / 255.0 test_images = test_images.reshape((-1, 28, 28, 1)) / 255.0 # 构建CNN模型 model = models.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels)) # 评估模型 test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) ``` 这段代码中,我们首先加载MNIST数据集,然后对数据进行预处理,将像素值缩放到[0, 1]的范围内。接着,我们构建了一个包含三个卷积层和两个全连接层的CNN模型,并使用`model.compile()`方法编译了模型,指定了优化器、损失函数和评估指标。最后,我们使用`model.fit()`方法训练模型,并在测试集上评估模型的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值