Convolutional Neural Network (CNN)

简介: 我自己写的代码和该教程略有不一样,有三处改动,第一个地方是用归一化(均值为0,方差为1)代替数值缩放([0, 1]),代替的理由是能提升准确率第二处改动是添加了正则化,在Conv2D和Dense Layer中均有添加,可以抑制模型过拟合,提升val_acc第三处改动是对模型训练五次进行acc取平均值,因为keras训练模型会有准确率波动,详细代码见文末链接

我自己写的代码和该教程略有不一样,有三处改动,第一个地方是用归一化(均值为0,方差为1)代替数值缩放([0, 1]),代替的理由是能提升准确率

第二处改动是添加了正则化,在Conv2D和Dense Layer中均有添加,可以抑制模型过拟合,提升val_acc

第三处改动是对模型训练五次进行acc取平均值,因为keras训练模型会有准确率波动,详细代码见文末链接

This tutorial demonstrates training a simple Convolutional Neural Network (CNN) to classify CIFAR images. Because this tutorial uses the Keras Sequential API, creating and training your model will take just a few lines of code.

Import TensorFlow

import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

Download and prepare the CIFAR10 dataset

The CIFAR10 dataset contains 60,000 color images in 10 classes, with 6,000 images in each class. The dataset is divided into 50,000 training images and 10,000 testing images. The classes are mutually exclusive and there is no overlap between them.

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

Verify the data

To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image:

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i])
    # The CIFAR labels happen to be arrays, 
    # which is why you need the extra index
    plt.xlabel(class_names[train_labels[i][0]])
plt.show()

Create the convolutional base

The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.

As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure your CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to your first layer.

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

Let's display the architecture of your model so far:

model.summary()

Above, you can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.

Add Dense layers on top

To complete the model, you will feed the last output tensor from the convolutional base (of shape (4, 4, 64)) into one or more Dense layers to perform classification. Dense layers take vectors as input (which are 1D), while the current output is a 3D tensor. First, you will flatten (or unroll) the 3D output to 1D, then add one or more Dense layers on top. CIFAR has 10 output classes, so you use a final Dense layer with 10 outputs.

model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

Here's the complete architecture of your model:

model.summary()

The network summary shows that (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.

Compile and train the model

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

Evaluate the model

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print(test_acc)

代码链接: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/CV_Classification/Convolutional%20Neural%20Network%20(CNN).ipynb

目录
相关文章
|
机器学习/深度学习 TensorFlow 语音技术
Convolutional Neural Network,简称 CNN
卷积神经网络(Convolutional Neural Network,简称 CNN)是一种深度学习模型,主要用于图像识别、物体检测、语音识别等任务。CNN 通过局部感知、权值共享和下采样等操作,能够有效地提取图像特征,从而实现对图像的分类和识别。
161 4
|
机器学习/深度学习 PyTorch TensorFlow
Convolutional Neural Network,简称 CNN
卷积神经网络(Convolutional Neural Network,简称 CNN)是一种特殊的神经网络结构,主要应用于图像识别、语音识别等领域。CNN 的特点是具有卷积层和池化层,能够从复杂数据中提取特征,降低计算复杂度,并实现平移不变性。
147 1
|
机器学习/深度学习 PyTorch TensorFlow
卷积神经网络(Convolutional Neural Network,CNN)
卷积神经网络(Convolutional Neural Network,CNN)是一种深度学习模型,特别适用于处理具有网格结构的数据,如图像和语音等。CNN的核心思想是通过卷积操作和池化操作来提取输入数据的特征,并通过全连接层进行分类或回归任务。
148 0
|
16天前
|
机器学习/深度学习 人工智能 自然语言处理
深度学习中的卷积神经网络(CNN)及其应用
【9月更文挑战第24天】本文将深入探讨深度学习中的一种重要模型——卷积神经网络(CNN)。我们将通过简单的代码示例,了解CNN的工作原理和应用场景。无论你是初学者还是有经验的开发者,这篇文章都将为你提供有价值的信息。
45 1
|
21天前
|
机器学习/深度学习 人工智能 自动驾驶
深度学习中的卷积神经网络(CNN)及其在图像识别中的应用
【9月更文挑战第19天】在人工智能的浩瀚星海中,卷积神经网络(CNN)如同一颗璀璨的星辰,照亮了图像处理的天空。本文将深入CNN的核心,揭示其在图像识别领域的强大力量。通过浅显易懂的语言和直观的比喻,我们将一同探索CNN的奥秘,并见证它如何在现实世界中大放异彩。
|
9天前
|
机器学习/深度学习 人工智能 算法框架/工具
深度学习中的卷积神经网络(CNN)及其在图像识别中的应用
【9月更文挑战第31天】本文旨在通过浅显易懂的语言和直观的比喻,为初学者揭开深度学习中卷积神经网络(CNN)的神秘面纱。我们将从CNN的基本原理出发,逐步深入到其在图像识别领域的实际应用,并通过一个简单的代码示例,展示如何利用CNN进行图像分类。无论你是编程新手还是深度学习的初学者,这篇文章都将为你打开一扇通往人工智能世界的大门。
|
10天前
|
机器学习/深度学习 人工智能 自然语言处理
深度学习中的卷积神经网络(CNN)入门与实践
【8月更文挑战第62天】本文以浅显易懂的方式介绍了深度学习领域中的核心技术之一——卷积神经网络(CNN)。文章通过生动的比喻和直观的图示,逐步揭示了CNN的工作原理和应用场景。同时,结合具体的代码示例,引导读者从零开始构建一个简单的CNN模型,实现对图像数据的分类任务。无论你是深度学习的初学者还是希望巩固理解的开发者,这篇文章都将为你打开一扇通往深度学习世界的大门。
|
21天前
|
机器学习/深度学习 人工智能 算法
深度学习中的卷积神经网络(CNN)入门与实践
【9月更文挑战第19天】在这篇文章中,我们将探索深度学习的一个重要分支——卷积神经网络(CNN)。从基础概念出发,逐步深入到CNN的工作原理和实际应用。文章旨在为初学者提供一个清晰的学习路径,并分享一些实用的编程技巧,帮助读者快速上手实践CNN项目。
|
20天前
|
机器学习/深度学习 自动驾驶 TensorFlow
深入理解卷积神经网络(CNN)在图像识别中的应用
【9月更文挑战第20天】本文旨在通过直观的解释和代码示例,向初学者介绍卷积神经网络(CNN)的基本概念及其在图像识别领域的应用。文章将首先解释什么是CNN以及它如何工作,然后通过一个简单的Python代码示例展示如何构建一个基本的CNN模型。最后,我们将讨论CNN在现实世界问题中的潜在应用,并探讨其面临的挑战和发展方向。
45 2
|
20天前
|
机器学习/深度学习 人工智能 算法
深入浅出卷积神经网络(CNN)
【9月更文挑战第20天】在人工智能的璀璨星河中,卷积神经网络(CNN)如同一颗耀眼的星辰,以其独特的魅力照亮了图像处理的天空。本文将带你遨游CNN的宇宙,从其诞生之初的微弱光芒,到成为深度学习领域的超级巨星,我们将一同探索它的结构奥秘、工作原理以及在实际场景中的惊艳应用。你将发现,CNN不仅仅是一段段代码和算法的堆砌,它更是一种让机器“看”懂世界的强大工具。让我们扣好安全带,一起深入CNN的世界,体验技术与创新交织的精彩旅程。

热门文章

最新文章