分析卷积神经网络图像识别过程和使用 Augmentation 解决 CNN 图像识别中的 Overfitting 问题 —— 以 Kaggle Dogs vs. Cats 为例

本文以Kaggle Dogs vs. Cats数据集为例,探讨卷积神经网络(CNN)在图像识别中的应用。通过介绍基本模型的构建,阐述CNN的工作原理。同时,针对过拟合问题,提出利用数据增强(Augmentation)方法,如旋转、拉伸等,增加训练数据多样性,有效提升模型泛化能力。
摘要由CSDN通过智能技术生成

本篇文章内容来自 Coursera: Convolutional Neural Networks in TensorFlow Week 1-2。提供方 deeplearning.ai,讲师 Laurence Moroney。

Case: 实现猫狗图像的智能识别,Dogs vs. Cats (已结束)


Code on GitHub 基本模型Augmentation

Code on Google Colab 基本模型Augmentation

Google Colab 类似一个在线的 IPython Notebook,不需要另外准备数据,但国内应该是需要梯子才能上。 GitHub 上提供了数据的路径和完整的 code。



接上一篇文章所说,我最近选择 DeepLearning.AI TensorFlow Developer 专业证书 作为接着 Machine Learning 后的另一个学习的项目。因为 Tensorflow 是主攻 Deep Learning,相比之前常用的 scikit-learn 中的工具还是有一些区别,并且在当下的 AI 大趋势下出现的频率越来越高,所以我就想分享一些我在学习中接触到的新的、容易上手的项目,帮助感兴趣的同学可以快速了解和运用这些工具,同时也可以帮助到未来失忆的我,hhh

基本模型

相比之前 Kaggle 上 Titanic 或者 House Price 的项目,这次的数据是以图片的形式存在的,所以它也有另外的标注方法。Keras 中使用的是通过将不同 category 数据存入不同文件路径实现 training set 数据的标注。以Dogs vs. Cats 为例,这里首先需要两层的分类。第一层将所有数据分为 training 和 testing,前者用于训练模型,后者用于 cross validation。第二层将 training 和 testing 中的数据归入 cats 和 dogs 实现数据的标注。
在这里插入图片描述
在数据的预处理中,如果数据来源只有 cats 和 dogs 两个分类,那么就需要按照一定的比例将原始数据随机的归入到 training set 和 testing set 中。下面的 code 主要就是实现了这一功能,(来自课程作业…)

# 这里假设原文件为两个文件夹,分别存有cats的图片文件和dogs的图片文件
# create directories
try:
    os.mkdir('/tmp/cats-v-dogs')
    os.mkdir('/tmp/cats-v-dogs/training')
    os.mkdir('/tmp/cats-v-dogs/testing')
    os.mkdir('/tmp/cats-v-dogs/training/cats')
    os.mkdir('/tmp/cats-v-dogs/training/dogs')
    os.mkdir('/tmp/cats-v-dogs/testing/cats')
    os.mkdir('/tmp/cats-v-dogs/testing/dogs')
except OSError:
    pass

这里有必要先筛选掉空白文件,以免在之后的模型处理中造成困难,

# 创建函数,首先移除无效文件,之后根据SPLIT_SIZE将原数据随机分入training和testing sets
def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):
	# SOURCE表示数据原文件
	# TRAINING和TESTING表示储存分离后文件的dictionaries
    files = []
    for filename in os.listdir(SOURCE):
        file = SOURCE + filename
        if os.path.getsize(file) > 0:
            files.append(filename)
        else:
            print(filename + " is zero length, so ignoring it!")
    
    training_length = int(len(files) * SPLIT_SIZE)
    testing_length = int(len(files) - training_length)
    shuffled_set = random.sample(files, len(files))
    training_set = shuffled_set[0:training_length]
    testing_set = shuffled_set[-testing_length:]
    
    for filename in training_set:
        this_file = SOURCE + filename
        destination = TRAINING + filename
        copyfile(this_file, destination)
        
    for filename in testing_set:
        this_file = SOURCE + filename
        destination = TESTING + filename
        copyfile(this_file, destination)
以下是使用MATLAB实现卷积神经网络图像识别的一般步骤: 1. 准备数据集:收集并准备图像数据集,将其分为训练集、验证集和测试集。 2. 加载和预处理数据:使用MATLAB的ImageDatastore函数加载和预处理数据集。 3. 定义网络结构:使用MATLAB的Deep Learning Toolbox的各种函数定义卷积神经网络的结构,例如convolution2dLayer、maxPooling2dLayer、fullyConnectedLayer等。 4. 配置训练选项:使用MATLAB的trainingOptions函数配置训练选项,例如学习率、最大训练轮数、优化器等。 5. 训练网络:使用MATLAB的trainNetwork函数训练网络。 6. 评估网络性能:使用MATLAB的classify函数评估网络在测试集上的性能。 7. 使用网络进行预测:使用MATLAB的classify函数使用训练好的网络进行预测。 下面是一个简单的MATLAB卷积神经网络图像识别的例子: ```matlab % 准备数据集 imds = imageDatastore('path/to/image/folder', 'IncludeSubfolders', true, 'LabelSource', 'foldernames'); [imdsTrain, imdsValidation, imdsTest] = splitEachLabel(imds, 0.7, 0.15, 0.15); % 加载和预处理数据 inputSize = [227 227 3]; augmenter = imageDataAugmenter('RandXReflection', true, 'RandXTranslation', [-10 10], 'RandYTranslation', [-10 10]); auimdsTrain = augmentedImageDatastore(inputSize, imdsTrain, 'DataAugmentation', augmenter); auimdsValidation = augmentedImageDatastore(inputSize, imdsValidation); auimdsTest = augmentedImageDatastore(inputSize, imdsTest); % 定义网络结构 layers = [ imageInputLayer(inputSize) convolution2dLayer(11, 96, 'Stride', 4, 'Padding', 0) reluLayer maxPooling2dLayer(3, 'Stride', 2) crossChannelNormalizationLayer(5) convolution2dLayer(5, 256, 'Stride', 1, 'Padding', 2) reluLayer maxPooling2dLayer(3, 'Stride', 2) crossChannelNormalizationLayer(5) convolution2dLayer(3, 384, 'Stride', 1, 'Padding', 1) reluLayer convolution2dLayer(3, 384, 'Stride', 1, 'Padding', 1) reluLayer convolution2dLayer(3, 256, 'Stride', 1, 'Padding', 1) reluLayer maxPooling2dLayer(3, 'Stride', 2) fullyConnectedLayer(4096) reluLayer dropoutLayer(0.5) fullyConnectedLayer(4096) reluLayer dropoutLayer(0.5) fullyConnectedLayer(numClasses) softmaxLayer classificationLayer]; % 配置训练选项 options = trainingOptions('sgdm', ... 'MiniBatchSize', 128, ... 'MaxEpochs', 20, ... 'InitialLearnRate', 0.001, ... 'Shuffle', 'every-epoch', ... 'ValidationData', auimdsValidation, ... 'ValidationFrequency', 10, ... 'Verbose', false, ... 'Plots', 'training-progress'); % 训练网络 net = trainNetwork(auimdsTrain, layers, options); % 评估网络性能 YPred = classify(net, auimdsTest); YTest = imdsTest.Labels; accuracy = sum(YPred == YTest)/numel(YTest) % 使用网络进行预测 im = imread('path/to/test/image'); im = imresize(im, inputSize(1:2)); YPred = classify(net, im); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值