PaddlePaddle tutorial Ⅴ——Cifar10 Convolutional Neural Networks

CIFAR10数据集上的图像分类:模型训练与VisualDL可视化
该博客介绍了使用PaddlePaddle进行CIFAR10数据集的图像分类任务。首先,通过Paddle的datasets模块获取并展示了数据集,接着对数据进行了预处理,包括归一化。然后,构建了一个包含卷积层、池化层和全连接层的简单CNN模型,并使用Adam优化器和交叉熵损失函数进行训练。训练过程中采用了VisualDL进行可视化,以便观察训练进度和指标。最后,模型在验证集上进行了评估,得到了约71.76%的准确率,并展示了每个类别准确率的条形图。
部署运行你感兴趣的模型镜像

数据获取

wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz

有关Cifar10数据的更多详细信息参见此篇博客,里面包含了详细的数据读取代码段以及数据文件介绍,为了方便起见,我们采用Paddle自带的datasets模块获取数据集

airplane
automobile
bird
cat
deer
dog
frog
horse
ship
truck

导入必要的包

import paddle
import math
import numpy as np
import matplotlib.pyplot as plt
import paddle.nn as nn
from paddle.vision.datasets import Cifar10
from paddle.vision.transforms import Normalize
import warnings
from paddle.io import Dataset
warnings.filterwarnings("ignore")

数据处理

定义字典,将数字标签与其名称对应起来

label_dict = {0:"airplane", 1:"automobile", 2:"bird", 3:"cat", 4:"deer",
              5:"dog", 6:"frog", 7:"horse", 8:"ship", 9:"truck"}

定义绘图函数,将图像数据可视化

def plot_num_images(num):
    if num < 1:
        print('INFO:The number of input pictures must be greater than zero!')
    else:
        choose_list = []
        for i in range(num):
            choose_n = np.random.randint(len(cifar10))
            choose_list.append(choose_n)
        fig = plt.gcf()
        fig.set_size_inches(15, 17)
        for i in range(num):
            ax_img = plt.subplot(math.ceil(num / 2), 5, i + 1)
            plt_img = cifar10[choose_list[i]][0]
            ax_img.imshow(plt_img, cmap='binary')
            ax_img.set_title(label_dict[cifar10[choose_list[i]][1].item()],
                             fontsize=20)
        plt.show()

cifar10 = Cifar10(mode='train', transform=None)

plot_num_images(10)

1

数据预处理,利用自定义的均值和方差将图像归一化

normalize = Normalize(mean=[127.5, 127.5, 127.5], 
                      std=[127.5, 127.5, 127.5],
                      data_format='HWC')
cifar10_train = Cifar10(mode='train', transform=normalize)
cifar10_val = Cifar10(mode='test', transform=normalize)

定义数据类

class Cifar10Dataset(Dataset):
    def __init__(self, mode='train'):
        super(Cifar10Dataset, self).__init__()
        if mode == 'train':
            self.data = [[cifar10_train[i][0].transpose(2, 0, 1).astype('float32'), cifar10_train[i][1].astype('int64')] for i in range(len(cifar10_train))]
        else:
            self.data = [[cifar10_val[i][0].transpose(2, 0, 1).astype('float32'), cifar10_val[i][1].astype('int64')] for i in range(len(cifar10_val))]

    def __getitem__(self, index):
        data = self.data[index][0]
        label = self.data[index][1]

        return data, label

    def __len__(self):
        return len(self.data)
train_loader = paddle.io.DataLoader(Cifar10Dataset(mode='train'), batch_size=1000, shuffle=True)
val_loader = paddle.io.DataLoader(Cifar10Dataset(mode='val'), batch_size=1000, shuffle=True)

建模训练

classification = paddle.nn.Sequential(
    paddle.nn.Conv2D(in_channels=3, 
                     out_channels=32,
                     kernel_size=(3, 3),
                     padding=1,
                     padding_mode='zeros'),
    paddle.nn.ReLU(),
    paddle.nn.Dropout(0.2),
    paddle.nn.MaxPool2D(2),
    paddle.nn.Conv2D(in_channels=32, 
                     out_channels=64,
                     kernel_size=(3, 3),
                     padding=1,
                     padding_mode='zeros'),
    paddle.nn.ReLU(),
    paddle.nn.Dropout(0.2),
    paddle.nn.MaxPool2D(2),
    paddle.nn.Flatten(),
    paddle.nn.Linear(in_features=4096, out_features=64),
    paddle.nn.Linear(in_features=64, out_features=10),
)

model = paddle.Model(classification)

模型摘要

model.summary((1, 3, 32, 32))
---------------------------------------------------------------------------
 Layer (type)       Input Shape          Output Shape         Param #    
===========================================================================
   Conv2D-1       [[1, 3, 32, 32]]     [1, 32, 32, 32]          896      
    ReLU-1       [[1, 32, 32, 32]]     [1, 32, 32, 32]           0       
   Dropout-1     [[1, 32, 32, 32]]     [1, 32, 32, 32]           0       
  MaxPool2D-1    [[1, 32, 32, 32]]     [1, 32, 16, 16]           0       
   Conv2D-2      [[1, 32, 16, 16]]     [1, 64, 16, 16]        18,496     
    ReLU-2       [[1, 64, 16, 16]]     [1, 64, 16, 16]           0       
   Dropout-2     [[1, 64, 16, 16]]     [1, 64, 16, 16]           0       
  MaxPool2D-2    [[1, 64, 16, 16]]      [1, 64, 8, 8]            0       
   Flatten-1      [[1, 64, 8, 8]]         [1, 4096]              0       
   Linear-1         [[1, 4096]]            [1, 64]            262,208    
   Linear-2          [[1, 64]]             [1, 10]              650      
===========================================================================
Total params: 282,250
Trainable params: 282,250
Non-trainable params: 0
---------------------------------------------------------------------------
Input size (MB): 0.01
Forward/backward pass size (MB): 1.25
Params size (MB): 1.08
Estimated Total Size (MB): 2.34
---------------------------------------------------------------------------






{'total_params': 282250, 'trainable_params': 282250}
model.prepare(optimizer=paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()),
              loss=paddle.nn.CrossEntropyLoss(),
              metrics=paddle.metric.Accuracy())
callback = paddle.callbacks.VisualDL(log_dir='log')
model.fit(train_loader,
          val_loader,
          epochs=50,
          batch_size=32,
          verbose=1,
          callbacks=callback)
The loss value printed in the log is the current step, and the metric is the average value of previous step.
Epoch 1/50
step 50/50 [==============================] - loss: 2.0034 - acc: 0.1965 - 160ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 2.0090 - acc: 0.3082 - 59ms/step
Eval samples: 10000
Epoch 2/50
step 50/50 [==============================] - loss: 1.5134 - acc: 0.3903 - 152ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 1.5198 - acc: 0.4750 - 60ms/step
Eval samples: 10000
Epoch 3/50
step 50/50 [==============================] - loss: 1.3807 - acc: 0.4915 - 151ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 1.3898 - acc: 0.5314 - 60ms/step
Eval samples: 10000
Epoch 4/50
step 50/50 [==============================] - loss: 1.2363 - acc: 0.5350 - 152ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 1.3221 - acc: 0.5538 - 60ms/step
Eval samples: 10000
Epoch 5/50
step 50/50 [==============================] - loss: 1.2591 - acc: 0.5620 - 153ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 1.2512 - acc: 0.5718 - 59ms/step
Eval samples: 10000
...
Epoch 45/50
step 50/50 [==============================] - loss: 0.6554 - acc: 0.7828 - 158ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.8406 - acc: 0.7103 - 61ms/step
Eval samples: 10000
Epoch 46/50
step 50/50 [==============================] - loss: 0.6264 - acc: 0.7862 - 155ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.8596 - acc: 0.7149 - 60ms/step
Eval samples: 10000
Epoch 47/50
step 50/50 [==============================] - loss: 0.5925 - acc: 0.7906 - 154ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.8046 - acc: 0.7147 - 61ms/step
Eval samples: 10000
Epoch 48/50
step 50/50 [==============================] - loss: 0.5864 - acc: 0.7932 - 154ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.8284 - acc: 0.7163 - 62ms/step
Eval samples: 10000
Epoch 49/50
step 50/50 [==============================] - loss: 0.6019 - acc: 0.7937 - 154ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.8471 - acc: 0.7165 - 61ms/step
Eval samples: 10000
Epoch 50/50
step 50/50 [==============================] - loss: 0.5827 - acc: 0.7946 - 153ms/step          
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 10/10 [==============================] - loss: 0.7734 - acc: 0.7176 - 61ms/step
Eval samples: 10000

模型验证

通过高阶API的evaluate进行评估

model.evaluate(Cifar10Dataset(mode='test'), batch_size=64, verbose=1)
Eval begin...
The loss value printed in the log is the current batch, and the metric is the average value of previous step.
step 157/157 [==============================] - loss: 0.8158 - acc: 0.7176 - 8ms/step          
Eval samples: 10000

{'loss': [0.8157779], 'acc': 0.7176}

获取每一类的准确率,利用predict对图像进行预测,由于是同一个测试集,可以发现predict准确率与evaluate相同,这也说明代码段的正确性

Correct_num = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
predict_onehot = model.predict(Cifar10Dataset(mode='test'), batch_size=100)
labels = np.array([cifar10_val[i][1].item() for i in range(len(cifar10_val))])
all_predict_result = []
for i in range(len(predict_onehot[0])):
    predict_result = np.argmax(predict_onehot[0][i], axis=1)
    all_predict_result = np.r_[all_predict_result, predict_result]
print('Acc:', sum(all_predict_result == labels) / len(cifar10_val))
Predict begin...
step 100/100 [==============================] - 11ms/step          
Predict samples: 10000
Acc: 0.7176
Correct_num = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}

for i in range(len(labels)):
    if all_predict_result[i] == labels[i]:
        Correct_num[labels[i]] += 1
Correct_rate = {}
for key in Correct_num:
    Correct_rate[label_dict[key]] = Correct_num[key] / sum(labels==key)
Correct_rate
{'airplane': 0.723,
 'automobile': 0.774,
 'bird': 0.57,
 'cat': 0.609,
 'deer': 0.732,
 'dog': 0.549,
 'frog': 0.769,
 'horse': 0.761,
 'ship': 0.858,
 'truck': 0.831}

可视化每一类图像准确率

fig = plt.gcf()
fig.set_size_inches(10, 5)
class_name = {'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog','frog', 'horse', 'ship', 'truck'}
plt.bar(range(10), [Correct_rate.get(class_name, 0) for class_name in class_name], align='center',yerr=0.000001)

plt.xticks(range(10), class_name)
plt.xlabel('Class Name')
plt.ylabel('Rate')
plt.title('Correct Rate of Each Class')
plt.show()

1

VIsualDL可视化

使用visualdl --logdir log查看训练日志

1

您可能感兴趣的与本文相关的镜像

PaddlePaddle-v3.3

PaddlePaddle-v3.3

PaddlePaddle

PaddlePaddle是由百度自主研发的深度学习平台,自 2016 年开源以来已广泛应用于工业界。作为一个全面的深度学习生态系统,它提供了核心框架、模型库、开发工具包等完整解决方案。目前已服务超过 2185 万开发者,67 万企业,产生了 110 万个模型

<think>好的,我现在需要帮用户找到卷积神经网络(CNN)的教程和实现示例。首先,用户提到了引用[1]和[2],其中引用[1]提到一个关于CNN在Keras框架中实现的教程链接,而引用[2]是关于TensorFlow中实现ConvNet的课程作业。用户可能需要详细的步骤和实践代码。 首先,我应该先确认用户的需求是学习CNN的基础知识还是具体的代码实现。根据问题描述,用户明确提到了“教程及其实现方法”,所以需要同时涵盖理论和实践部分。接下来,我需要整理CNN的关键知识点,比如卷积层、池化层、全连接层,以及它们在框架中的实现方式。 然后,考虑用户可能使用的框架。引用中提到了Keras和TensorFlow,所以需要分别给出这两个框架的示例。Keras更简洁,适合快速实现,而TensorFlow则更灵活,适合深入理解。另外,用户可能需要了解数据预处理、模型构建、训练和评估的整个流程。 接下来,我需要检查提供的引用内容是否有直接可用的资源。引用[1]提到了一个教程链接,但用户可能无法访问外部链接,所以应该将关键步骤和代码示例整合到回答中。同时,引用[3]提到了反向传播和优化器,这部分可以在训练过程中解释,比如使用随机梯度下降和交叉熵损失函数。 用户的问题还可能涉及到如何应用CNN到实际项目中,比如图像分类。因此,给出一个具体的例子,如MNIST手写数字识别,会有助于用户理解。需要确保代码示例正确,并解释每一部分的作用,比如卷积层的参数、激活函数的选择、池化操作的影响等。 最后,生成相关问题时,要考虑用户可能进一步想知道的内容,比如超参数调优、数据增强、模型评估指标等。这些问题可以帮助用户深入学习,解决实际应用中可能遇到的挑战。 需要确保回答结构清晰,分步骤讲解,并且代码格式正确,符合用户提供的系统级指令,比如数学表达式用$...$,独立公式用$$...$$。同时,引用标识要正确添加到对应的参考内容末尾,保持自然。</think>### 卷积神经网络(CNN)教程与实现方法 卷积神经网络(CNN)是处理图像、语音等网格数据的核心模型,其核心结构包括卷积层、池化层和全连接层。以下是实现步骤和示例代码: --- #### 1. **CNN核心组件** - **卷积层**:通过滤波器(如$3\times3$或$5\times5$)提取局部特征,数学表示为: $$(f * g)(i,j) = \sum_{m}\sum_{n} f(m,n)g(i-m,j-n)$$ 其中$f$为输入,$g$为滤波器[^3]。 - **池化层**(如最大池化):降低维度,增强平移不变性。 - **激活函数**:常用ReLU($f(x) = \max(0,x)$)解决梯度消失问题。 --- #### 2. **Keras实现示例(图像分类)** ```python from tensorflow.keras import layers, models # 构建模型 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.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)) ``` **代码说明**: - 使用MNIST数据集(手写数字分类) - 卷积层提取边缘/纹理特征,池化层压缩特征图 - 交叉熵损失函数最小化分类误差[^3] --- #### 3. **TensorFlow实现(自定义层)** ```python import tensorflow as tf class CustomConvLayer(tf.keras.layers.Layer): def __init__(self, filters, kernel_size): super().__init__() self.conv = tf.keras.layers.Conv2D(filters, kernel_size, activation='relu') self.pool = tf.keras.layers.MaxPool2D() def call(self, inputs): x = self.conv(inputs) return self.pool(x) # 构建完整模型 model = tf.keras.Sequential([ CustomConvLayer(32, (3,3)), CustomConvLayer(64, (3,3)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) ``` **特点**:支持自定义层结构,灵活调整超参数[^2] --- #### 4. **关键优化技巧** - **数据增强**:旋转/平移图像增加泛化性 - **批归一化**:加速训练收敛 - **Dropout**:防止过拟合(如在全连接层前添加`layers.Dropout(0.5)`) ---
评论 1
添加红包
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值