利用CNN(卷积神经网络)训练mnist数据集

本文参考了经典的LeNet-5卷积神经网络模型对mnist数据集进行训练。LeNet-5模型是大神Yann LeCun于1998年在论文"Gradient-based learning applied to document recognition"中提出来的,它是第一个成功应用于数字识别问题的卷积神经网络。下图展示了LeNet-5模型的架构。


文中所使用的卷积神经网络结构依次为输入层,卷积层1,池化层1,卷积层2,池化层2,全连接层1,全连接层2,输出层。

"""A very simple MNIST classifier.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beginners
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import numpy as np
import tensorflow as tf
data_dir = './data/'
mnist = input_data.read_data_sets(data_dir, one_hot=True)
#第一层卷积层尺寸和深度
CONV_1_SIZE = 3    
CONV_1_DEEP = 32  
INPUT_CHANNELS = 1 #输入通道数

#第二层卷积层尺寸和深度
CONV_2_SIZE = 3
CONV_2_DEEP = 64

#每批次数据集的大小
BATCH_SIZE = 100

#学习率
LEARNING_RATE_INIT = 1e-3    #学习率初始值
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

#对输入向量x转换成图像矩阵形式
with tf.variable_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1]) #因为数据的条数未知,所以为-1

#卷积层1
with tf.variable_scope('conv1'):
    initial_value = tf.truncated_normal([CONV_1_SIZE,CONV_1_SIZE,INPUT_CHANNELS,CONV_1_DEEP], stddev=0.1)
    conv_1_w = tf.Variable(initial_value=initial_value, collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'WEIGHTS'])
    conv_1_b = tf.Variable(initial_value=tf.constant(0.1, shape=[CONV_1_DEEP]))
    conv_1_l = tf.nn.conv2d(x_image, conv_1_w, strides=[1,1,1,1], padding='SAME') + conv_1_b
    conv_1_h = tf.nn.relu(conv_1_l)

#池化层1
with tf.variable_scope('pool1'):
    pool_1_h = tf.nn.max_pool(conv_1_h, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')

#卷积层2
with tf.variable_scope('conv2'):
    conv_2_w = tf.Variable(tf.truncated_normal([CONV_2_SIZE,CONV_2_SIZE,CONV_1_DEEP,CONV_2_DEEP], stddev=0.1),
                           collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'WEIGHTS'])
    conv_2_b = tf.Variable(tf.constant(0.1, shape=[CONV_2_DEEP]))
    conv_2_l = tf.nn.conv2d(pool_1_h, conv_2_w, strides=[1,1,1,1], padding='SAME') + conv_2_b
    conv_2_h = tf.nn.relu(conv_2_l)

#池化层2
with tf.name_scope('pool2'):
    pool_2_h = tf.nn.max_pool(conv_2_h, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')

#全连接层1
with tf.name_scope('fc1'):
    #
    fc_1_w = tf.Variable(tf.truncated_normal([7*7*64, 1024], stddev=0.1))
    fc_1_b = tf.Variable(tf.constant(0.1, shape=[1024]))
    #全连接层的输入为向量,而池化层2的输出为7x7x64的矩阵,所以这里要将矩阵转化成一个向量
    pool_2_h_flat = tf.reshape(pool_2_h, [-1,7*7*64])
    fc_1_h = tf.nn.relu(tf.matmul(pool_2_h_flat, fc_1_w) + fc_1_b)
    
#dropout在训练时会随机将部分节点的输出改为0,以避免过拟合问题,从而使得模型在测试数据上的效果更好
#dropout一般只在全连接层而不是卷积层或者池化层使用
with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    fc_1_h_drop = tf.nn.dropout(fc_1_h, keep_prob)
    
#全连接层2 And 输出层
with tf.name_scope('fc2'):
    fc_2_w = tf.Variable(tf.truncated_normal([1024,10], stddev=0.1), collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'WEIGHTS'])
    fc_2_b = tf.Variable(tf.constant(0.1, shape=[10]))
    y = tf.matmul(fc_1_h_drop, fc_2_w) + fc_2_b
    
#交叉熵
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

#l2正则项
l2_loss = tf.add_n([tf.nn.l2_loss(w) for w in tf.get_collection('WEIGHTS')])

#代价函数 = 交叉熵加上惩罚项
total_loss = cross_entropy + 7e-5*l2_loss

#定义一个Adam优化器
train_step = tf.train.AdamOptimizer(LEARNING_RATE_INIT).minimize(total_loss)

sess = tf.InteractiveSession()
init_op = tf.global_variables_initializer()
sess.run(init_op)

#Train
for step in range(5000):
    batch_xs, batch_ys = mnist.train.next_batch(BATCH_SIZE)
    _, loss, l2_loss_value, total_loss_value = sess.run(
        [train_step, cross_entropy, l2_loss, total_loss],
        feed_dict={x: batch_xs, y_:batch_ys, keep_prob:0.5})
    
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #
    if (step+1)%200 == 0:
        #每隔200步评估一下训练集和测试集
        train_accuracy = accuracy.eval(feed_dict={x:batch_xs, y_:batch_ys, keep_prob:1.0})
        test_accuracy = accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})
        print("step:%d, loss:%f, train_acc:%f, test_acc:%f" % (step, total_loss_value, train_accuracy, test_accuracy))

输出:


好的,我可以为您提供一份基于PyTorch实现LeNet-5模型的代码,并使用FashionMNIST数据集进行训练。 首先,您需要安装PyTorch和torchvision库,以便使用LeNet-5模型和FashionMNIST数据集。您可以使用以下命令在终端中安装它们: ``` pip install torch pip install torchvision ``` 然后,您可以使用以下代码来定义LeNet-5模型: ```python import torch.nn as nn import torch.nn.functional as F class LeNet5(nn.Module): def __init__(self): super(LeNet5, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1) self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.fc1 = nn.Linear(16 * 4 * 4, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool1(F.relu(self.conv1(x))) x = self.pool2(F.relu(self.conv2(x))) x = x.view(-1, 16 * 4 * 4) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x ``` 这个LeNet-5模型定义了两个卷积层和三个全连接层。在forward()函数中,我们使用ReLU激活函数和max pooling操作来提取特征,并将特征传递到全连接层中进行分类。 接下来,您可以使用以下代码来加载FashionMNIST数据集并进行训练: ```python import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torchvision.datasets as datasets # 定义一些超参数 batch_size = 64 learning_rate = 0.01 num_epochs = 10 # 加载FashionMNIST数据集 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) train_dataset = datasets.FashionMNIST(root='./data', train=True, transform=transform, download=True) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # 实例化LeNet-5模型和损失函数 model = LeNet5() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=learning_rate) # 训练模型 for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): # 前向传播和反向传播 outputs = model(images) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() # 每100步打印一次日志 if (i + 1) % 100 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, i + 1, len(train_loader), loss.item())) ``` 在这个训练循环中,我们首先使用SGD优化器和交叉熵损失函数实例化了LeNet-5模型。然后,我们将FashionMNIST数据集加载到train_loader中,并使用train_loader在每个epoch中进行训练。对于每个batch,我们首先执行前向传播,计算输出和损失,然后执行反向传播并更新模型参数。最后,我们在每个epoch的日志中记录损失值。 希望这个代码对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值