当前位置: 首页 > news >正文

福建省网站备案贵阳市住房和城乡建设厅网站

福建省网站备案,贵阳市住房和城乡建设厅网站,郑州做网站汉狮网络,免费活动策划方案的网站Pytorch | 从零构建EfficientNet对CIFAR10进行分类 CIFAR10数据集EfficientNet设计理念网络结构性能特点应用领域发展和改进 EfficientNet结构代码详解结构代码代码详解MBConv 类初始化方法前向传播 forward 方法 EfficientNet 类初始化方法前向传播 forward 方法 训练过程和测… Pytorch | 从零构建EfficientNet对CIFAR10进行分类 CIFAR10数据集EfficientNet设计理念网络结构性能特点应用领域发展和改进 EfficientNet结构代码详解结构代码代码详解MBConv 类初始化方法前向传播 forward 方法 EfficientNet 类初始化方法前向传播 forward 方法 训练过程和测试结果代码汇总efficientnet.pytrain.pytest.py 前面文章我们构建了AlexNet、Vgg、GoogleNet、ResNet、MobileNet对CIFAR10进行分类 Pytorch | 从零构建AlexNet对CIFAR10进行分类 Pytorch | 从零构建Vgg对CIFAR10进行分类 Pytorch | 从零构建GoogleNet对CIFAR10进行分类 Pytorch | 从零构建ResNet对CIFAR10进行分类 Pytorch | 从零构建MobileNet对CIFAR10进行分类 这篇文章我们来构建EfficientNet. CIFAR10数据集 CIFAR-10数据集是由加拿大高级研究所CIFAR收集整理的用于图像识别研究的常用数据集基本信息如下 数据规模该数据集包含60,000张彩色图像分为10个不同的类别每个类别有6,000张图像。通常将其中50,000张作为训练集用于模型的训练10,000张作为测试集用于评估模型的性能。图像尺寸所有图像的尺寸均为32×32像素这相对较小的尺寸使得模型在处理该数据集时能够相对快速地进行训练和推理但也增加了图像分类的难度。类别内容涵盖了飞机plane、汽车car、鸟bird、猫cat、鹿deer、狗dog、青蛙frog、马horse、船ship、卡车truck这10个不同的类别这些类别都是现实世界中常见的物体具有一定的代表性。 下面是一些示例样本 EfficientNet EfficientNet是由谷歌大脑团队在2019年提出的一种高效的卷积神经网络架构在图像分类等任务上展现出了卓越的性能和效率以下是对它的详细介绍 设计理念 平衡模型的深度、宽度和分辨率传统的神经网络在提升性能时往往只是单纯地增加网络的深度、宽度或输入图像的分辨率而EfficientNet则通过一种系统的方法同时对这三个维度进行优化调整以达到在计算资源有限的情况下模型性能的最大化。 网络结构 MBConv模块EfficientNet的核心模块是MBConvMobile Inverted Residual Bottleneck它基于深度可分离卷积和倒置残差结构。这种结构在减少计算量的同时能够有效提取图像特征提高模型的表示能力。Compound Scaling方法使用该方法对网络的深度、宽度和分辨率进行统一缩放。通过一个固定的缩放系数同时调整这三个维度使得模型在不同的计算资源限制下都能保持较好的性能和效率平衡。 上图中是EfficientNet-B0的结构. 性能特点 高效性在相同的计算资源下EfficientNet能够取得比传统网络更好的性能。例如与ResNet-50相比EfficientNet-B0在ImageNet数据集上取得了相近的准确率但参数量和计算量却大大减少。可扩展性通过Compound Scaling方法可以方便地调整模型的大小以适应不同的应用场景和计算资源限制。从EfficientNet-B0到EfficientNet-B7模型的复杂度逐渐增加性能也相应提升能够满足从移动端到服务器端的不同需求。 应用领域 图像分类在ImageNet等大规模图像分类数据集上EfficientNet取得了领先的性能成为图像分类任务的首选模型之一。目标检测与Faster R-CNN等目标检测框架结合EfficientNet作为骨干网络能够提高目标检测的准确率和速度在Pascal VOC、COCO等数据集上取得了不错的效果。语义分割在语义分割任务中EfficientNet也展现出了一定的优势通过与U-Net等分割网络结合能够对图像进行像素级的分类在Cityscapes等数据集上有较好的表现。 发展和改进 EfficientNet v2在EfficientNet基础上进行了进一步优化主要改进包括改进了渐进式学习的方法在训练过程中逐渐增加图像的分辨率使得模型能够更好地学习到不同尺度的特征同时优化了网络结构提高了模型的训练速度和性能。其他改进研究人员还在EfficientNet的基础上结合其他技术如注意力机制、知识蒸馏等进一步提高模型的性能和泛化能力。 EfficientNet结构代码详解 结构代码 import torch import torch.nn as nn import torch.nn.functional as Fclass MBConv(nn.Module):def __init__(self, in_channels, out_channels, expand_ratio, kernel_size, stride, padding, se_ratio0.25):super(MBConv, self).__init__()self.stride strideself.use_res_connect (stride 1 and in_channels out_channels)# 扩展通道数如果需要expanded_channels in_channels * expand_ratioself.expand_conv nn.Conv2d(in_channels, expanded_channels, kernel_size1, padding0, biasFalse)self.bn1 nn.BatchNorm2d(expanded_channels)# 深度可分离卷积self.depthwise_conv nn.Conv2d(expanded_channels, expanded_channels, kernel_sizekernel_size,stridestride, paddingpadding, groupsexpanded_channels, biasFalse)self.bn2 nn.BatchNorm2d(expanded_channels)# 压缩和激励SE模块可选根据se_ratio判断是否添加if se_ratio 0:se_channels int(in_channels * se_ratio)self.se nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Conv2d(expanded_channels, se_channels, kernel_size1),nn.ReLU(inplaceTrue),nn.Conv2d(se_channels, expanded_channels, kernel_size1),nn.Sigmoid())else:self.se None# 投影卷积恢复到输出通道数self.project_conv nn.Conv2d(expanded_channels, out_channels, kernel_size1, padding0, biasFalse)self.bn3 nn.BatchNorm2d(out_channels)def forward(self, x):identity x# 扩展通道数out F.relu(self.bn1(self.expand_conv(x)))# 深度可分离卷积out F.relu(self.bn2(self.depthwise_conv(out)))# SE模块操作如果存在if self.se is not None:se_out self.se(out)out out * se_out# 投影卷积out self.bn3(self.project_conv(out))# 残差连接如果满足条件if self.use_res_connect:out identityreturn outclass EfficientNet(nn.Module):def __init__(self, num_classes, width_coefficient1.0, depth_coefficient1.0, dropout_rate0.2):super(EfficientNet, self).__init__()self.stem_conv nn.Conv2d(3, 32, kernel_size3, stride2, padding1, biasFalse)self.bn1 nn.BatchNorm2d(32)mbconv_config [# (in_channels, out_channels, expand_ratio, kernel_size, stride, padding)(32, 16, 1, 3, 1, 1),(16, 24, 6, 3, 2, 1),(24, 40, 6, 5, 2, 2),(40, 80, 6, 3, 2, 1),(80, 112, 6, 5, 1, 2),(112, 192, 6, 5, 2, 2),(192, 320, 6, 3, 1, 1)]# 根据深度系数调整每个MBConv模块的重复次数这里简单地向下取整你也可以根据实际情况采用更合理的方式repeat_counts [max(1, int(depth_coefficient * 1)) for _ in mbconv_config]layers []for i, config in enumerate(mbconv_config):in_channels, out_channels, expand_ratio, kernel_size, stride, padding configfor _ in range(repeat_counts[i]):layers.append(MBConv(int(in_channels * width_coefficient),int(out_channels * width_coefficient),expand_ratio, kernel_size, stride, padding))self.mbconv_layers nn.Sequential(*layers)self.last_conv nn.Conv2d(int(320 * width_coefficient), 1280, kernel_size1, biasFalse)self.bn2 nn.BatchNorm2d(1280)self.avgpool nn.AdaptiveAvgPool2d(1)self.dropout nn.Dropout(dropout_rate)self.fc nn.Linear(1280, num_classes)def forward(self, x):out F.relu(self.bn1(self.stem_conv(x)))out self.mbconv_layers(out)out F.relu(self.bn2(self.last_conv(out)))out self.avgpool(out)out out.view(out.size(0), -1)out self.dropout(out)out self.fc(out)return out代码详解 以下是对上述EfficientNet代码的详细解释代码整体定义了EfficientNet网络结构主要由MBConv模块堆叠以及一些常规的卷积、池化和全连接层构成下面按照类和方法分别进行剖析 MBConv 类 这是EfficientNet中的核心模块实现了MBConvMobile Inverted Residual Bottleneck Convolution结构其代码如下 class MBConv(nn.Module):def __init__(self, in_channels, out_channels, expand_ratio, kernel_size, stride, padding, se_ratio0.25):super(MBConv, self).__init__()self.stride strideself.use_res_connect (stride 1 and in_channels out_channels)# 扩展通道数如果需要expanded_channels in_channels * expand_ratioself.expand_conv nn.Conv2d(in_channels, expanded_channels, kernel_size1, padding0, biasFalse)self.bn1 nn.BatchNorm2d(expanded_channels)# 深度可分离卷积self.depthwise_conv nn.Conv2d(expanded_channels, expanded_channels, kernel_sizekernel_size,stridestride, paddingpadding, groupsexpanded_channels, biasFalse)self.bn2 nn.BatchNorm2d(expanded_channels)# 压缩和激励SE模块可选根据se_ratio判断是否添加if se_ratio 0:se_channels int(in_channels * se_ratio)self.se nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Conv2d(expanded_channels, se_channels, kernel_size1),nn.ReLU(inplaceTrue),nn.Conv2d(se_channels, expanded_channels, kernel_size1),nn.Sigmoid())else:self.se None# 投影卷积恢复到输出通道数self.project_conv nn.Conv2d(expanded_channels, out_channels, kernel_size1, padding0, biasFalse)self.bn3 nn.BatchNorm2d(out_channels)def forward(self, x):identity x# 扩展通道数out F.relu(self.bn1(self.expand_conv(x)))# 深度可分离卷积out F.relu(self.bn2(self.depthwise_conv(out)))# SE模块操作如果存在if self.se is not None:se_out self.se(out)out out * se_out# 投影卷积out self.bn3(self.project_conv(out))# 残差连接如果满足条件if self.use_res_connect:out identityreturn out初始化方法 参数说明 in_channels输入张量的通道数。out_channels输出张量的通道数。expand_ratio用于确定扩展通道数时的比例系数决定是否对输入通道数进行扩展以及扩展的倍数。kernel_size卷积核的大小用于深度可分离卷积等操作。stride卷积的步长控制特征图在卷积过程中的下采样程度等。padding卷积操作时的填充大小保证输入输出特征图尺寸在特定要求下的一致性等。se_ratio可选默认值为0.25用于控制压缩和激励SE模块中通道压缩的比例若为0则不添加SE模块。 初始化操作 首先保存传入的stride参数并根据stride和输入输出通道数判断是否使用残差连接use_res_connect只有当步长为1且输入输出通道数相等时才使用残差连接这符合残差网络的基本原理有助于梯度传播和特征融合。根据expand_ratio计算扩展后的通道数expanded_channels并创建expand_conv卷积层用于扩展通道数同时搭配对应的bn1批归一化层对扩展后的特征进行归一化处理有助于加速网络收敛和提升模型稳定性。定义depthwise_conv深度可分离卷积层其分组数设置为expanded_channels意味着每个通道单独进行卷积操作这种方式可以在减少计算量的同时保持较好的特征提取能力同时搭配bn2批归一化层。根据se_ratio判断是否添加压缩和激励SE模块。如果se_ratio大于0则创建一个包含自适应平均池化、卷积、激活函数ReLU、卷积和Sigmoid激活的序列模块se用于对特征进行通道维度上的重加权增强模型对不同通道特征的关注度若se_ratio为0则将se设为None。最后创建project_conv投影卷积层用于将扩展和处理后的特征恢复到指定的输出通道数并搭配bn3批归一化层。 前向传播 forward 方法 首先将输入张量x保存为identity用于后续可能的残差连接。通过F.relu(self.bn1(self.expand_conv(x)))对输入进行通道扩展并使用ReLU激活函数和批归一化进行处理得到扩展后的特征表示。接着对扩展后的特征执行深度可分离卷积操作F.relu(self.bn2(self.depthwise_conv(out)))同样使用ReLU激活和批归一化处理。如果存在SE模块self.se不为None则将经过深度可分离卷积后的特征传入SE模块进行通道重加权即se_out self.se(out)然后将特征与重加权后的结果相乘out out * se_out。通过self.bn3(self.project_conv(out))进行投影卷积操作将特征恢复到输出通道数并进行批归一化处理。最后如果满足残差连接条件self.use_res_connect为True则将投影卷积后的特征与最初保存的输入特征identity相加实现残差连接最终返回处理后的特征张量。 EfficientNet 类 这是整体的EfficientNet网络模型类代码如下 class EfficientNet(nn.Module):def __init__(self, num_classes, width_coefficient1.0, depth_coefficient1.0, dropout_rate0.2):super(EfficientNet, self).__init__()self.stem_conv nn.Conv2d(3, 32, kernel_size3, stride2, padding1, biasFalse)self.bn1 nn.BatchNorm2d(32)mbconv_config [# (in_channels, out_channels, expand_ratio, kernel_size, stride, padding)(32, 16, 1, 3, 1, 1),(16, 24, 6, 3, 2, 1),(24, 40, 6, 5, 2, 2),(40, 80, 6, 3, 2, 1),(80, 112, 6, 5, 1, 2),(112, 192, 6, 5, 2, 2),(192, 320, 6, 3, 1, 1)]# 根据深度系数调整每个MBConv模块的重复次数这里简单地向下取整你也可以根据实际情况采用更合理的方式repeat_counts [max(1, int(depth_coefficient * 1)) for _ in mbconv_config]layers []for i, config in enumerate(mbconv_config):in_channels, out_channels, expand_ratio, kernel_size, stride, padding configfor _ in range(repeat_counts[i]):layers.append(MBConv(int(in_channels * width_coefficient),int(out_channels * width_coefficient),expand_ratio, kernel_size, stride, padding))self.mbconv_layers nn.Sequential(*layers)self.last_conv nn.Conv2d(int(320 * width_coefficient), 1280, kernel_size1, biasFalse)self.bn2 nn.BatchNorm2d(1280)self.avgpool nn.AdaptiveAvgPool2d(1)self.dropout nn.Dropout(dropout_rate)self.fc nn.Linear(1280, num_classes)def forward(self, x):out F.relu(self.bn1(self.stem_conv(x)))out self.mbconv_layers(out)out F.relu(self.bn2(self.last_conv(out)))out self.avgpool(out)out out.view(out.size(0), -1)out self.dropout(out)out self.fc(out)return out初始化方法 参数说明 num_classes最终分类任务的类别数量用于确定全连接层的输出维度。width_coefficient默认值为1.0用于控制模型各层的通道数实现对模型宽度的缩放调整。depth_coefficient默认值为1.0用于控制模型中MBConv模块的重复次数实现对模型深度的缩放调整。dropout_rate默认值为0.2在全连接层之前使用的Dropout概率用于防止过拟合。 初始化操作 首先创建stem_conv卷积层它将输入的图像数据通常通道数为3对应RGB图像进行初始的卷积操作步长为2起到下采样的作用同时不使用偏置biasFalse并搭配bn1批归一化层对卷积后的特征进行归一化处理。定义mbconv_config列表其中每个元素是一个元组包含了MBConv模块的各项配置参数如输入通道数、输出通道数、扩展比例、卷积核大小、步长和填充等这是构建MBConv模块的基础配置信息。根据depth_coefficient计算每个MBConv模块的重复次数通过列表推导式 repeat_counts [max(1, int(depth_coefficient * 1)) for _ in mbconv_config] 实现这里简单地将每个配置对应的重复次数设置为与depth_coefficient成比例向下取整且保证至少重复1次你可以根据更精细的设计规则来调整这个计算方式。构建self.mbconv_layers通过两层嵌套循环实现。外层循环遍历mbconv_config配置列表内层循环根据对应的重复次数来多次添加同一个MBConv模块实例到layers列表中最后将layers列表转换为nn.Sequential类型的模块这样就实现了根据depth_coefficient对模型深度进行调整以及MBConv模块的堆叠搭建。创建last_conv卷积层它将经过MBConv模块处理后的特征进行进一步的卷积操作将通道数转换为1280同样不使用偏置搭配bn2批归一化层。定义avgpool自适应平均池化层将特征图转换为固定大小这里为1x1方便后续全连接层处理。创建dropout Dropout层按照指定的dropout_rate在全连接层之前进行随机失活操作防止过拟合。最后定义fc全连接层其输入维度为1280经过池化后的特征维度输出维度为num_classes用于最终的分类预测。 前向传播 forward 方法 首先将输入x传入stem_conv卷积层进行初始卷积然后通过F.relu(self.bn1(self.stem_conv(x)))进行激活和批归一化处理得到初始的特征表示。将初始特征传入self.mbconv_layers即经过一系列堆叠的MBConv模块进行特征提取和变换充分挖掘图像中的特征信息。接着对经过MBConv模块处理后的特征执行F.relu(self.bn2(self.last_conv(out)))操作进行最后的卷积以及激活、批归一化处理。使用self.avgpool(out)进行自适应平均池化将特征图尺寸变为1x1实现特征的压缩和固定维度表示。通过out out.view(out.size(0), -1)将池化后的特征张量展平为一维向量方便全连接层处理这里-1表示自动根据张量元素总数和已知的批量大小维度out.size(0)来推断展平后的维度大小。然后将展平后的特征传入self.dropout(out)进行Dropout操作随机丢弃一部分神经元防止过拟合。最后将特征传入self.fc(out)全连接层进行分类预测得到最终的输出结果输出的维度与设定的num_classes一致表示每个样本属于各个类别的预测概率或得分等具体取决于任务和后续处理并返回该输出结果。 训练过程和测试结果 训练过程损失函数变化曲线 训练过程准确率变化曲线 测试结果 代码汇总 项目github地址 项目结构 |--data |--models|--__init__.py|-efficientnet.py|--... |--results |--weights |--train.py |--test.pyefficientnet.py import torch import torch.nn as nn import torch.nn.functional as Fclass MBConv(nn.Module):def __init__(self, in_channels, out_channels, expand_ratio, kernel_size, stride, padding, se_ratio0.25):super(MBConv, self).__init__()self.stride strideself.use_res_connect (stride 1 and in_channels out_channels)# 扩展通道数如果需要expanded_channels in_channels * expand_ratioself.expand_conv nn.Conv2d(in_channels, expanded_channels, kernel_size1, padding0, biasFalse)self.bn1 nn.BatchNorm2d(expanded_channels)# 深度可分离卷积self.depthwise_conv nn.Conv2d(expanded_channels, expanded_channels, kernel_sizekernel_size,stridestride, paddingpadding, groupsexpanded_channels, biasFalse)self.bn2 nn.BatchNorm2d(expanded_channels)# 压缩和激励SE模块可选根据se_ratio判断是否添加if se_ratio 0:se_channels int(in_channels * se_ratio)self.se nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Conv2d(expanded_channels, se_channels, kernel_size1),nn.ReLU(inplaceTrue),nn.Conv2d(se_channels, expanded_channels, kernel_size1),nn.Sigmoid())else:self.se None# 投影卷积恢复到输出通道数self.project_conv nn.Conv2d(expanded_channels, out_channels, kernel_size1, padding0, biasFalse)self.bn3 nn.BatchNorm2d(out_channels)def forward(self, x):identity x# 扩展通道数out F.relu(self.bn1(self.expand_conv(x)))# 深度可分离卷积out F.relu(self.bn2(self.depthwise_conv(out)))# SE模块操作如果存在if self.se is not None:se_out self.se(out)out out * se_out# 投影卷积out self.bn3(self.project_conv(out))# 残差连接如果满足条件if self.use_res_connect:out identityreturn outclass EfficientNet(nn.Module):def __init__(self, num_classes, width_coefficient1.0, depth_coefficient1.0, dropout_rate0.2):super(EfficientNet, self).__init__()self.stem_conv nn.Conv2d(3, 32, kernel_size3, stride2, padding1, biasFalse)self.bn1 nn.BatchNorm2d(32)mbconv_config [# (in_channels, out_channels, expand_ratio, kernel_size, stride, padding)(32, 16, 1, 3, 1, 1),(16, 24, 6, 3, 2, 1),(24, 40, 6, 5, 2, 2),(40, 80, 6, 3, 2, 1),(80, 112, 6, 5, 1, 2),(112, 192, 6, 5, 2, 2),(192, 320, 6, 3, 1, 1)]# 根据深度系数调整每个MBConv模块的重复次数这里简单地向下取整你也可以根据实际情况采用更合理的方式repeat_counts [max(1, int(depth_coefficient * 1)) for _ in mbconv_config]layers []for i, config in enumerate(mbconv_config):in_channels, out_channels, expand_ratio, kernel_size, stride, padding configfor _ in range(repeat_counts[i]):layers.append(MBConv(int(in_channels * width_coefficient),int(out_channels * width_coefficient),expand_ratio, kernel_size, stride, padding))self.mbconv_layers nn.Sequential(*layers)self.last_conv nn.Conv2d(int(320 * width_coefficient), 1280, kernel_size1, biasFalse)self.bn2 nn.BatchNorm2d(1280)self.avgpool nn.AdaptiveAvgPool2d(1)self.dropout nn.Dropout(dropout_rate)self.fc nn.Linear(1280, num_classes)def forward(self, x):out F.relu(self.bn1(self.stem_conv(x)))out self.mbconv_layers(out)out F.relu(self.bn2(self.last_conv(out)))out self.avgpool(out)out out.view(out.size(0), -1)out self.dropout(out)out self.fc(out)return outtrain.py import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from models import * import matplotlib.pyplot as pltimport ssl ssl._create_default_https_context ssl._create_unverified_context# 定义数据预处理操作 transform transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.491, 0.482, 0.446), (0.247, 0.243, 0.261))])# 加载CIFAR10训练集 trainset torchvision.datasets.CIFAR10(root./data, trainTrue,downloadFalse, transformtransform) trainloader torch.utils.data.DataLoader(trainset, batch_size128,shuffleTrue, num_workers2)# 定义设备GPU优先若可用 device torch.device(cuda if torch.cuda.is_available() else cpu)# 实例化模型 model_name EfficientNet if model_name AlexNet:model AlexNet(num_classes10).to(device) elif model_name Vgg_A:model Vgg(cfg_vggA, num_classes10).to(device) elif model_name Vgg_A-LRN:model Vgg(cfg_vggA-LRN, num_classes10).to(device) elif model_name Vgg_B:model Vgg(cfg_vggB, num_classes10).to(device) elif model_name Vgg_C:model Vgg(cfg_vggC, num_classes10).to(device) elif model_name Vgg_D:model Vgg(cfg_vggD, num_classes10).to(device) elif model_name Vgg_E:model Vgg(cfg_vggE, num_classes10).to(device) elif model_name GoogleNet:model GoogleNet(num_classes10).to(device) elif model_name ResNet18:model ResNet18(num_classes10).to(device) elif model_name ResNet34:model ResNet34(num_classes10).to(device) elif model_name ResNet50:model ResNet50(num_classes10).to(device) elif model_name ResNet101:model ResNet101(num_classes10).to(device) elif model_name ResNet152:model ResNet152(num_classes10).to(device) elif model_name MobileNet:model MobileNet(num_classes10).to(device) elif model_name EfficientNet:model EfficientNet(num_classes10).to(device)criterion nn.CrossEntropyLoss() optimizer optim.Adam(model.parameters(), lr0.001)# 训练轮次 epochs 15def train(model, trainloader, criterion, optimizer, device):model.train()running_loss 0.0correct 0total 0for i, data in enumerate(trainloader, 0):inputs, labels data[0].to(device), data[1].to(device)optimizer.zero_grad()outputs model(inputs)loss criterion(outputs, labels)loss.backward()optimizer.step()running_loss loss.item()_, predicted outputs.max(1)total labels.size(0)correct predicted.eq(labels).sum().item()epoch_loss running_loss / len(trainloader)epoch_acc 100. * correct / totalreturn epoch_loss, epoch_accif __name__ __main__:loss_history, acc_history [], []for epoch in range(epochs):train_loss, train_acc train(model, trainloader, criterion, optimizer, device)print(fEpoch {epoch 1}: Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.2f}%)loss_history.append(train_loss)acc_history.append(train_acc)# 保存模型权重每5轮次保存到weights文件夹下if (epoch 1) % 5 0:torch.save(model.state_dict(), fweights/{model_name}_epoch_{epoch 1}.pth)# 绘制损失曲线plt.plot(range(1, epochs1), loss_history, labelLoss, markero)plt.xlabel(Epoch)plt.ylabel(Loss)plt.title(Training Loss Curve)plt.legend()plt.savefig(fresults\\{model_name}_train_loss_curve.png)plt.close()# 绘制准确率曲线plt.plot(range(1, epochs1), acc_history, labelAccuracy, markero)plt.xlabel(Epoch)plt.ylabel(Accuracy (%))plt.title(Training Accuracy Curve)plt.legend()plt.savefig(fresults\\{model_name}_train_acc_curve.png)plt.close()test.py import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from models import *import ssl ssl._create_default_https_context ssl._create_unverified_context # 定义数据预处理操作 transform transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.491, 0.482, 0.446), (0.247, 0.243, 0.261))])# 加载CIFAR10测试集 testset torchvision.datasets.CIFAR10(root./data, trainFalse,downloadFalse, transformtransform) testloader torch.utils.data.DataLoader(testset, batch_size128,shuffleFalse, num_workers2)# 定义设备GPU优先若可用 device torch.device(cuda if torch.cuda.is_available() else cpu)# 实例化模型 model_name EfficientNet if model_name AlexNet:model AlexNet(num_classes10).to(device) elif model_name Vgg_A:model Vgg(cfg_vggA, num_classes10).to(device) elif model_name Vgg_A-LRN:model Vgg(cfg_vggA-LRN, num_classes10).to(device) elif model_name Vgg_B:model Vgg(cfg_vggB, num_classes10).to(device) elif model_name Vgg_C:model Vgg(cfg_vggC, num_classes10).to(device) elif model_name Vgg_D:model Vgg(cfg_vggD, num_classes10).to(device) elif model_name Vgg_E:model Vgg(cfg_vggE, num_classes10).to(device) elif model_name GoogleNet:model GoogleNet(num_classes10).to(device) elif model_name ResNet18:model ResNet18(num_classes10).to(device) elif model_name ResNet34:model ResNet34(num_classes10).to(device) elif model_name ResNet50:model ResNet50(num_classes10).to(device) elif model_name ResNet101:model ResNet101(num_classes10).to(device) elif model_name ResNet152:model ResNet152(num_classes10).to(device) elif model_name MobileNet:model MobileNet(num_classes10).to(device) elif model_name EfficientNet:model EfficientNet(num_classes10).to(device)criterion nn.CrossEntropyLoss()# 加载模型权重 weights_path fweights/{model_name}_epoch_15.pth model.load_state_dict(torch.load(weights_path, map_locationdevice))def test(model, testloader, criterion, device):model.eval()running_loss 0.0correct 0total 0with torch.no_grad():for data in testloader:inputs, labels data[0].to(device), data[1].to(device)outputs model(inputs)loss criterion(outputs, labels)running_loss loss.item()_, predicted outputs.max(1)total labels.size(0)correct predicted.eq(labels).sum().item()epoch_loss running_loss / len(testloader)epoch_acc 100. * correct / totalreturn epoch_loss, epoch_accif __name__ __main__:test_loss, test_acc test(model, testloader, criterion, device)print(f{model_name} Test)print(fLoad Model Weights From: {weights_path})print(fTest Loss: {test_loss:.4f}, Test Acc: {test_acc:.2f}%)
文章转载自:
http://www.morning.cpqqf.cn.gov.cn.cpqqf.cn
http://www.morning.tnbsh.cn.gov.cn.tnbsh.cn
http://www.morning.ydnx.cn.gov.cn.ydnx.cn
http://www.morning.nwgkk.cn.gov.cn.nwgkk.cn
http://www.morning.pghfy.cn.gov.cn.pghfy.cn
http://www.morning.rqhdt.cn.gov.cn.rqhdt.cn
http://www.morning.cpnsh.cn.gov.cn.cpnsh.cn
http://www.morning.rltsx.cn.gov.cn.rltsx.cn
http://www.morning.pxmyw.cn.gov.cn.pxmyw.cn
http://www.morning.jtszm.cn.gov.cn.jtszm.cn
http://www.morning.frmmp.cn.gov.cn.frmmp.cn
http://www.morning.kjmws.cn.gov.cn.kjmws.cn
http://www.morning.mstbbs.com.gov.cn.mstbbs.com
http://www.morning.hwzzq.cn.gov.cn.hwzzq.cn
http://www.morning.dnqlba.cn.gov.cn.dnqlba.cn
http://www.morning.pshtf.cn.gov.cn.pshtf.cn
http://www.morning.ncrk.cn.gov.cn.ncrk.cn
http://www.morning.junyaod.com.gov.cn.junyaod.com
http://www.morning.lkhfm.cn.gov.cn.lkhfm.cn
http://www.morning.kqbjy.cn.gov.cn.kqbjy.cn
http://www.morning.gxhqt.cn.gov.cn.gxhqt.cn
http://www.morning.flqbg.cn.gov.cn.flqbg.cn
http://www.morning.epeij.cn.gov.cn.epeij.cn
http://www.morning.wnjbn.cn.gov.cn.wnjbn.cn
http://www.morning.pylpd.cn.gov.cn.pylpd.cn
http://www.morning.qkdcb.cn.gov.cn.qkdcb.cn
http://www.morning.jxscp.cn.gov.cn.jxscp.cn
http://www.morning.gtcym.cn.gov.cn.gtcym.cn
http://www.morning.mzwqt.cn.gov.cn.mzwqt.cn
http://www.morning.c7617.cn.gov.cn.c7617.cn
http://www.morning.fyglg.cn.gov.cn.fyglg.cn
http://www.morning.pcngq.cn.gov.cn.pcngq.cn
http://www.morning.nzdks.cn.gov.cn.nzdks.cn
http://www.morning.huayaosteel.cn.gov.cn.huayaosteel.cn
http://www.morning.zqkms.cn.gov.cn.zqkms.cn
http://www.morning.gslz.com.cn.gov.cn.gslz.com.cn
http://www.morning.dpdr.cn.gov.cn.dpdr.cn
http://www.morning.jhqcr.cn.gov.cn.jhqcr.cn
http://www.morning.lpmjr.cn.gov.cn.lpmjr.cn
http://www.morning.deanzhu.com.gov.cn.deanzhu.com
http://www.morning.qrsm.cn.gov.cn.qrsm.cn
http://www.morning.fjshyc.com.gov.cn.fjshyc.com
http://www.morning.qhmgq.cn.gov.cn.qhmgq.cn
http://www.morning.rdpps.cn.gov.cn.rdpps.cn
http://www.morning.bjjrtcsl.com.gov.cn.bjjrtcsl.com
http://www.morning.xmyrn.cn.gov.cn.xmyrn.cn
http://www.morning.ktblf.cn.gov.cn.ktblf.cn
http://www.morning.tgdys.cn.gov.cn.tgdys.cn
http://www.morning.cprbp.cn.gov.cn.cprbp.cn
http://www.morning.krswn.cn.gov.cn.krswn.cn
http://www.morning.hlnys.cn.gov.cn.hlnys.cn
http://www.morning.rknhd.cn.gov.cn.rknhd.cn
http://www.morning.nlkjq.cn.gov.cn.nlkjq.cn
http://www.morning.ywpwq.cn.gov.cn.ywpwq.cn
http://www.morning.rbkdg.cn.gov.cn.rbkdg.cn
http://www.morning.xgcwm.cn.gov.cn.xgcwm.cn
http://www.morning.nkqrq.cn.gov.cn.nkqrq.cn
http://www.morning.wsyq.cn.gov.cn.wsyq.cn
http://www.morning.tfpbm.cn.gov.cn.tfpbm.cn
http://www.morning.mdjtk.cn.gov.cn.mdjtk.cn
http://www.morning.wqmyh.cn.gov.cn.wqmyh.cn
http://www.morning.trqsm.cn.gov.cn.trqsm.cn
http://www.morning.ssfq.cn.gov.cn.ssfq.cn
http://www.morning.mwqbp.cn.gov.cn.mwqbp.cn
http://www.morning.srwny.cn.gov.cn.srwny.cn
http://www.morning.rkypb.cn.gov.cn.rkypb.cn
http://www.morning.cnfxr.cn.gov.cn.cnfxr.cn
http://www.morning.ydnx.cn.gov.cn.ydnx.cn
http://www.morning.pkmw.cn.gov.cn.pkmw.cn
http://www.morning.mbbgk.com.gov.cn.mbbgk.com
http://www.morning.jfnbh.cn.gov.cn.jfnbh.cn
http://www.morning.xdpjf.cn.gov.cn.xdpjf.cn
http://www.morning.wrlxt.cn.gov.cn.wrlxt.cn
http://www.morning.fbylq.cn.gov.cn.fbylq.cn
http://www.morning.ckhpg.cn.gov.cn.ckhpg.cn
http://www.morning.dmwck.cn.gov.cn.dmwck.cn
http://www.morning.fwqgy.cn.gov.cn.fwqgy.cn
http://www.morning.lqytk.cn.gov.cn.lqytk.cn
http://www.morning.gqflj.cn.gov.cn.gqflj.cn
http://www.morning.kqpxb.cn.gov.cn.kqpxb.cn
http://www.tj-hxxt.cn/news/264533.html

相关文章:

  • 大庆网站开发阿里云多网站建设
  • q版设计网站北恩uc3客户管理软件
  • 网站建设具体工作数据网站建设工具模板
  • 个人网站备案都需要什么项目之家
  • 网站设计培训商城网站建设是什么
  • 太仓住房与城乡建设局网站wordpress 关闭警告
  • 购物网站排名前十网站开发语言一般是用什么
  • html5手机网站制作软件医疗网络营销方式
  • 做网站推广的销售电话开场白wordpress编辑器没有编辑框
  • 企业门户网站数据库设计网站建设销售工资多少
  • 360网站建设官网怎么建设分销模式手机网站
  • 我想做一个网站怎么办wordpress保存为模板
  • 网站内容与模板设计方案西安做网站需要多少钱
  • 网站备案花钱么购物网站二级店铺mvc
  • 销售网站看男科花了一万多了
  • 专业网站建设网站推广wordpress后天打开慢
  • 电商网站设计模板dw一个人怎么开发自己的app
  • 微小店网站建设平台谷歌网页截图快捷键
  • 佛山智能建站重庆自动seo
  • 上海企业建站公司哪家好平面设计专业课程有哪些
  • 响应式网站建设公司学校网站建设问卷调查表
  • 唐山网站制作案例深圳计算机速成班培训
  • 东莞网站建设总部地址做网站公司599
  • 单页网站赚钱七牛镜像存储wordpress
  • 做趣味图形的网站北京工程交易中心官网
  • 国外的网页制作网站wordpress查资料
  • 公明网站建设传媒大学附近网站建设公司
  • 济南市工程建设技术监督局网站建设工作室
  • 东营网站建设优化留言小程序模板
  • 网站开发行业怎么样网站安全建设进展情况汇报