ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

彩色图片分类

彩色图片分类 前言我的环境语言环境Python 3.10.14编译器jupyter notebook深度学习环境TensorFlow 2.17.0一、导入数据这段代码是用于导入TensorFlow库、Keras中的模块手动下载并加载CIFAR-10数据集的Python脚本。CIFAR-10是一个常用的机器学习数据集它包含了10个类别的60000张32x32的彩色图像。import os import pickle import numpy as np import matplotlib.pyplot as plt # 指定解压后的数据集路径 cifar10_dir C:/Users/27437/Desktop/cifar-10-batches-py # 定义一个函数来加载 CIFAR-10 数据集的单个批次 def load_cifar10_batch(file): with open(file, rb) as f: datadict pickle.load(f, encodinglatin1) X datadict[data] Y datadict[labels] # 将图像数据重塑并转置使其符合 (num_images, height, width, channels) 的形状 X X.reshape(10000, 3, 32, 32).transpose(0, 2, 3, 1).astype(float) # 将标签转换为 NumPy 数组 Y np.array(Y) return X, Y # 加载训练集和测试集 train_files [os.path.join(cifar10_dir, data_batch_ str(i)) for i in range(1, 6)] test_file os.path.join(cifar10_dir, test_batch) # 初始化空数组来存储训练和测试数据 train_images np.concatenate([load_cifar10_batch(file)[0] for file in train_files]) train_labels np.concatenate([load_cifar10_batch(file)[1] for file in train_files]) test_images, test_labels load_cifar10_batch(test_file) # 归一化图像数据到 [0, 1] 范围内 train_images train_images / 255.0 test_images test_images / 255.0 # 确保标签是正确的形状 train_labels train_labels.reshape(-1, 1) test_labels test_labels.reshape(-1, 1) # 输出数据的形状 print(train_images.shape, test_images.shape, train_labels.shape, test_labels.shape)二、可视化用于可视化CIFAR-10数据集中前20张训练图像的Python脚本并且每张图像下方会显示对应的类别名称。以下是代码的逐行解释class_names [airplane, automobile, bird, cat, deer,dog, frog, horse, ship, truck]定义一个列表class_names包含了CIFAR-10数据集中所有类别的名称。plt.figure(figsize(20,10))创建一个新的matplotlib图形设置图形的大小为20x10英寸。for i in range(20):使用for循环遍历前20张图像。plt.subplot(5,10,i1)在图形中创建子图5行10列的布局总共50个子图当前循环的索引i1确定子图的位置。plt.xticks([])和plt.yticks([])移除子图的x轴和y轴的刻度。plt.grid(False)关闭子图的网格线。plt.imshow(train_images[i], cmapplt.cm.binary)显示第i张图像使用二值颜色映射黑白。plt.xlabel(class_names[train_labels[i][0]])设置子图的x轴标签为对应的类别名称train_labels[i][0]是第i张图像的类别索引。plt.show()显示图形。class_names [airplane, automobile, bird, cat, deer,dog, frog, horse, ship, truck] plt.figure(figsize(20,10)) for i in range(20): plt.subplot(5,10,i1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmapplt.cm.binary) plt.xlabel(class_names[train_labels[i][0]]) plt.show()三、构建CNN网络1.池化层池化层对提取到的特征信息进行降维一方面使特征图变小简化网络计算复杂度另一方面进行特征压缩提取主要特征增加平移不变性减少过拟合风险。但其实池化更多程度上是一种计算性能的一个妥协强硬地压缩特征的同时也损失了一部分信息所以现在的网络比较少用池化层或者使用优化后的如SoftPool。池化层包括最大池化层MaxPooling和平均池化层AveragePooling均值池化对背景保留更好最大池化对纹理提取更好。同卷积计算池化层计算窗口内的平均值或者最大值。例如通过一个 2*2 的最大池化层其计算方式如下model models.Sequential([ layers.Conv2D(32, (3, 3), activationrelu, input_shape(32, 32, 3)), #卷积层1卷积核3*3 layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activationrelu), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activationrelu), layers.Flatten(), layers.Dense(64, activationrelu), layers.Dense(10) ]) model.summary()这段代码定义了一个使用 TensorFlow 和 Keras 构建的卷积神经网络CNN模型。这个模型适用于处理图像数据比如 CIFAR-10 数据集它包含 32x32 像素的彩色图像。下面是模型中每一层的详细解释Sequential 模型models.Sequential()是一个线性堆叠的层次模型用于创建顺序模型。第一层卷积层Convolutional Layerlayers.Conv2D(32, (3, 3), activationrelu, input_shape(32, 32, 3))32过滤器卷积核的数量每个过滤器会生成一个特征图。(3, 3)每个过滤器的大小即 3x3 的卷积核。activationrelu激活函数使用 ReLURectified Linear Unit函数。input_shape(32, 32, 3)输入数据的形状即 32x32 的图像3 个颜色通道。第二层最大池化层Max Pooling Layerlayers.MaxPooling2D((2, 2))(2, 2)池化窗口的大小即 2x2。这一层将每个特征图的空间维度减半。第三层卷积层layers.Conv2D(64, (3, 3), activationrelu)64过滤器的数量增加到 64。其他参数与第一层相同。第四层最大池化层layers.MaxPooling2D((2, 2))与第二层相同。第五层卷积层layers.Conv2D(64, (3, 3), activationrelu)与第三层相同。第六层展平层Flatten Layerlayers.Flatten()将多维输入一维化以便可以被全连接层处理。第七层全连接层Dense Layerlayers.Dense(64, activationrelu)64神经元的数量。activationrelu使用 ReLU 激活函数。第八层全连接层layers.Dense(10)10输出层神经元的数量对应于 CIFAR-10 数据集中的 10 个类别。没有指定激活函数因此默认为线性激活函数。模型概览model.summary()打印模型的概览包括每层的输出形状和模型的总参数数量。池化层包括最大池化层MaxPooling和平均池化层AveragePooling均值池化对背景保留更好最大池化对纹理提取更好。同卷积计算池化层计算窗口内的平均值或者最大值。例如通过一个 2*2 的最大池化层其计算方式如下四、编译训练模型1.编译和训练编译和训练之前定义的卷积神经网络模型的。下面是代码中每个部分的详细解释模型编译Model Compilationmodel.compile()是在训练模型之前必须调用的一个方法用于配置模型的学习过程。optimizeradam指定优化器。这里使用的是 Adam 优化器它是一种基于梯度下降的优化算法能够自动调整学习率通常表现良好是许多深度学习任务的首选优化器。losstf.keras.losses.SparseCategoricalCrossentropy(from_logitsTrue)指定损失函数。这里使用的是SparseCategoricalCrossentropy它适用于多分类问题其中目标类别是整数。from_logitsTrue表示损失函数期望的输入是未经 softmax 激活的 logits即模型输出层的原始输出。metrics[accuracy]指定评估模型性能的指标。这里使用的是准确率accuracy即正确分类的样本占总样本的比例。模型训练Model Trainingmodel.fit()是用于训练模型的方法。train_images和train_labels分别是训练集的输入数据和标签。epochs10指定训练的轮数。每个 epoch 都会遍历一次完整的训练数据。validation_data(test_images, test_labels)指定用于验证模型性能的数据集。在每个 epoch 结束时模型会在这些数据上评估损失和准确率这有助于监控模型在未见过的数据上的表现并防止过拟合。model.compile(optimizeradam, losstf.keras.losses.SparseCategoricalCrossentropy(from_logitsTrue), metrics[accuracy]) history model.fit(train_images, train_labels, epochs10, validation_data(test_images, test_labels)) plt.imshow(test_images[1])2.评估模型绘制训练和验证准确率plt.plot(history.history[accuracy], labelaccuracy)绘制训练准确率曲线。history.history[accuracy]包含了每个 epoch 结束时的训练准确率。plt.plot(history.history[val_accuracy], labelval_accuracy)绘制验证准确率曲线。history.history[val_accuracy]包含了每个 epoch 结束时的验证准确率。设置图表标签和标题plt.xlabel(Epoch)设置 x 轴标签为 Epoch。plt.ylabel(Accuracy)设置 y 轴标签为 Accuracy。plt.ylim([0.5, 1])设置 y 轴的范围为 0.5 到 1这样可以更清晰地看到准确率的变化。plt.legend(loclower right)添加图例位于图表的右下角。评估模型在测试集上的性能test_loss, test_acc model.evaluate(test_images, test_labels, verbose2)使用测试集评估模型的性能。test_loss测试集上的损失值。test_acc测试集上的准确率。verbose2设置日志显示模式verbose2表示在控制台中显示详细的进度信息。import numpy as np pre model.predict(test_images) print(class_names[np.argmax(pre[1])]) import matplotlib.pyplot as plt plt.plot(history.history[accuracy], labelaccuracy) plt.plot(history.history[val_accuracy], label val_accuracy) plt.xlabel(Epoch) plt.ylabel(Accuracy) plt.ylim([0.5, 1]) plt.legend(loclower right) plt.show() test_loss, test_acc model.evaluate(test_images, test_labels, verbose2)print(test_acc)打印测试集上的准确率
返回列表