深度学习Week20——Pytorch实现残差网络和ResNet50V2算法

文章目录
深度学习Week20——Pytorch实现残差网络和ResNet50V2算法
一、前言
二、我的环境
三、代码复现
3.1 配置数据集
3.2 构建模型
四、模型应用与评估
4.1 编写训练函数
4.2 编写测试函数
4.3 训练模型
4.4 结果可视化

一、前言

  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊 | 接辅导、项目定制

本周我们使用了Pytorch复现代码。

二、我的环境

  • 电脑系统:Windows 10
  • 语言环境:Python 3.8.0
  • 编译器:Pycharm2023.2.3
    深度学习环境:Pytorch
    显卡及显存:RTX 3060 8G

三、代码复现

3.1 配置数据集

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warningswarnings.filterwarnings("ignore")             #忽略警告信息device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
data_dir = "/home/mw/input/data7619//bird_photos/bird_photos"data_dir = pathlib.Path(data_dir)data_paths  = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[0] for path in data_paths]
print(classeNames)
['/home/mw/input/data7619/bird_photos/bird_photos/Bananaquit', '/home/mw/input/data7619/bird_photos/bird_photos/Black Throated Bushtiti', '/home/mw/input/data7619/bird_photos/bird_photos/Cockatoo', '/home/mw/input/data7619/bird_photos/bird_photos/Black Skimmer']
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)

图片总数为: 565
数据增强
import torchvision.transforms as transforms
from torchvision import datasets# 这里我们运用上前面学习到的数据增强的方式
train_transforms = transforms.Compose([transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸transforms.RandomHorizontalFlip(),  # 随机水平翻转transforms.RandomVerticalFlip(),  # 随机垂直翻转transforms.RandomRotation(15),  # 随机旋转图片,范围为-15度到15度transforms.ToTensor(),  # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
])test_transform = transforms.Compose([transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸transforms.ToTensor(),  # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间transforms.Normalize(  # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])total_data = datasets.ImageFolder("/home/mw/input/data7619//bird_photos/bird_photos", transform=train_transforms)
print(total_data.class_to_idx)
{'Bananaquit': 0, 'Black Skimmer': 1, 'Black Throated Bushtiti': 2, 'Cockatoo': 3}
划分训练集、测试集
# 按比例将数据集分割为训练集和测试集
train_size = int(0.8 * len(total_data))  # 计算训练集的大小,占总数据集的80%
test_size = len(total_data) - train_size  # 计算测试集的大小,占总数据集的20%
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])  # 随机分割数据集# 定义批量大小
batch_size = 32# 创建训练集的数据加载器
train_dl = torch.utils.data.DataLoader(train_dataset,  # 训练集数据batch_size=batch_size,  # 每个批次的大小为32shuffle=True,  # 打乱数据num_workers=0  # 使用的工作线程数
)# 创建测试集的数据加载器
test_dl = torch.utils.data.DataLoader(test_dataset,  batch_size=batch_size,  shuffle=True,  num_workers=0  
)for X, y in test_dl:print("Shape of X [N, C, H, W]: ", X.shape) print("Shape of y: ", y.shape, y.dtype)  break  
Shape of X [N, C, H, W]:  torch.Size([32, 3, 224, 224])
Shape of y:  torch.Size([32]) torch.int64

2、 构建模型

首先我们需要定义残差块(block2)和堆栈(stack2),然后创建ResNet50V2模型。

class Block2(nn.Module):def __init__(self, in_channels, filters, stride=1, conv_shortcut=False):super(Block2, self).__init__()self.conv_shortcut = conv_shortcutself.preact_bn = nn.BatchNorm2d(in_channels)self.preact_relu = nn.ReLU(inplace=True)if conv_shortcut:self.shortcut = nn.Conv2d(in_channels, 4 * filters, kernel_size=1, stride=stride)else:self.shortcut = nn.Identity()if stride > 1:self.shortcut = nn.MaxPool2d(kernel_size=1, stride=stride)self.conv1 = nn.Conv2d(in_channels, filters, kernel_size=1, stride=1, bias=False)self.bn1 = nn.BatchNorm2d(filters)self.conv2 = nn.Conv2d(filters, filters, kernel_size=3, stride=stride, padding=1, bias=False)self.bn2 = nn.BatchNorm2d(filters)self.conv3 = nn.Conv2d(filters, 4 * filters, kernel_size=1)def forward(self, x):shortcut = self.shortcut(x)x = self.preact_bn(x)x = self.preact_relu(x)x = self.conv1(x)x = self.bn1(x)x = F.relu(x)x = self.conv2(x)x = self.bn2(x)x = F.relu(x)x = self.conv3(x)x += shortcutreturn xclass Stack2(nn.Module):def __init__(self, in_channels, filters, blocks, stride1=2):super(Stack2, self).__init__()self.blocks = nn.ModuleList()self.blocks.append(Block2(in_channels, filters, stride=stride1, conv_shortcut=True))for _ in range(1, blocks):self.blocks.append(Block2(4 * filters, filters))def forward(self, x):for block in self.blocks:x = block(x)return xclass ResNet50V2(nn.Module):def __init__(self, num_classes=1000, include_top=True):super(ResNet50V2, self).__init__()self.include_top = include_topself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)self.bn1 = nn.BatchNorm2d(64)self.relu = nn.ReLU(inplace=True)self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)self.conv2 = Stack2(64, 64, 3, stride1=1)self.conv3 = Stack2(256, 128, 4)self.conv4 = Stack2(512, 256, 6)self.conv5 = Stack2(1024, 512, 3, stride1=1)self.post_bn = nn.BatchNorm2d(2048)self.post_relu = nn.ReLU(inplace=True)if include_top:self.avgpool = nn.AdaptiveAvgPool2d((1, 1))self.fc = nn.Linear(2048, num_classes)def forward(self, x):x = self.conv1(x)x = self.bn1(x)x = self.relu(x)x = self.maxpool(x)x = self.conv2(x)x = self.conv3(x)x = self.conv4(x)x = self.conv5(x)x = self.post_bn(x)x = self.post_relu(x)if self.include_top:x = self.avgpool(x)x = torch.flatten(x, 1)x = self.fc(x)return xif __name__ == '__main__':model = ResNet50V2(num_classes=1000)print(model)
ResNet50V2((conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(relu): ReLU(inplace=True)(maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)(conv2): Stack2((blocks): ModuleList((0): Block2((preact_bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1))(conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1)))(1): Block2((preact_bn): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1)))(2): Block2((preact_bn): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1)))))(conv3): Stack2((blocks): ModuleList((0): Block2((preact_bn): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2))(conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1)))(1): Block2((preact_bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1)))(2): Block2((preact_bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1)))(3): Block2((preact_bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1)))))(conv4): Stack2((blocks): ModuleList((0): Block2((preact_bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2))(conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))(1): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))(2): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))(3): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))(4): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))(5): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1)))))(conv5): Stack2((blocks): ModuleList((0): Block2((preact_bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(1, 1))(conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1)))(1): Block2((preact_bn): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1)))(2): Block2((preact_bn): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(preact_relu): ReLU(inplace=True)(shortcut): Identity()(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1)))))(post_bn): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(post_relu): ReLU(inplace=True)(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))(fc): Linear(in_features=2048, out_features=1000, bias=True)
)

四 、模型应用与评估

4.1 编写训练函数

def train(dataloader, model, loss_fn, optimizer):model.train()train_loss, train_acc = 0, 0for X, y in dataloader:X, y = X.to(device), y.to(device)# 计算预测误差pred = model(X)loss = loss_fn(pred, y)# 反向传播optimizer.zero_grad()loss.backward()optimizer.step()train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc  /= len(dataloader.dataset)train_loss /= len(dataloader)return train_acc, train_loss

4.2 编写测试函数

def test(dataloader, model, loss_fn):model.eval()test_loss, test_acc = 0, 0with torch.no_grad():for X, y in dataloader:X, y = X.to(device), y.to(device)pred = model(X)loss = loss_fn(pred, y)test_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()test_loss += loss.item()test_acc  /= len(dataloader.dataset)test_loss /= len(dataloader)return test_acc, test_loss

4.3 训练模型

import copy
import torch.nn.functional as Foptimizer  = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数epochs = 10train_loss = []
train_acc = []
test_loss = []
test_acc = []best_acc = 0  # 设置一个最佳准确率,作为最佳模型的判别指标for epoch in range(epochs):# 更新学习率(使用自定义学习率时使用)# adjust_learning_rate(optimizer, epoch, learn_rate)model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)# scheduler.step() # 更新学习率(调用官方动态学习率接口时使用)model.eval()epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)# 保存最佳模型到 best_modelif epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model)train_acc.append(epoch_train_acc)train_loss.append(epoch_train_loss)test_acc.append(epoch_test_acc)test_loss.append(epoch_test_loss)# 获取当前的学习率lr = optimizer.state_dict()['param_groups'][0]['lr']template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss,epoch_test_acc * 100, epoch_test_loss, lr))# 保存最佳模型到文件中
PATH = './best_model.pth'  # 保存的参数文件名
torch.save(model.state_dict(), PATH)print('Done')

Epoch: 1, Train_acc:51.8%, Train_loss:4.475, Test_acc:27.4%, Test_loss:5.794, Lr:1.00E-04
Epoch: 2, Train_acc:73.2%, Train_loss:1.766, Test_acc:30.1%, Test_loss:4.920, Lr:1.00E-04
Epoch: 3, Train_acc:79.0%, Train_loss:0.846, Test_acc:54.0%, Test_loss:2.211, Lr:1.00E-04
Epoch: 4, Train_acc:81.0%, Train_loss:0.567, Test_acc:76.1%, Test_loss:0.809, Lr:1.00E-04
Epoch: 5, Train_acc:85.8%, Train_loss:0.428, Test_acc:78.8%, Test_loss:0.761, Lr:1.00E-04
Epoch: 6, Train_acc:83.0%, Train_loss:0.473, Test_acc:79.6%, Test_loss:0.725, Lr:1.00E-04
Epoch: 7, Train_acc:83.6%, Train_loss:0.530, Test_acc:77.9%, Test_loss:0.620, Lr:1.00E-04
Epoch: 8, Train_acc:85.0%, Train_loss:0.479, Test_acc:78.8%, Test_loss:0.830, Lr:1.00E-04
Epoch: 9, Train_acc:85.6%, Train_loss:0.434, Test_acc:82.3%, Test_loss:0.824, Lr:1.00E-04
Epoch:10, Train_acc:88.5%, Train_loss:0.396, Test_acc:70.8%, Test_loss:0.865, Lr:1.00E-04
Done

4.4 结果可视化

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率epochs_range = range(epochs)plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/3246876.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

昇思25天学习打卡营第 12 天 | mindspore 实现 ResNet50 图像分类

1. 背景: 使用 mindspore 学习神经网络,打卡第 12 天;主要内容也依据 mindspore 的学习记录。 2. ResNet 介绍: mindspore 实现 ResNet50 图像分类; ResNet 基本介绍: Residual Networks 是微软研究院 K…

港股指数实时行情API接口

港股 指数 实时 行情 API接口 # Restful API https://tsanghi.com/api/fin/index/HKG/realtime?token{token}&ticker{ticker}指定指数代码,获取该指数的实时行情(开、高、低、收、量)。 更新周期:实时。 请求方式&#xff1a…

GuLi商城-商品服务-API-属性分组-分组修改级联选择器回显

前端代码:略 后端回显接口: 递归方法: @Override publi

linux进程——父子进程层面的PID,fork的原理与理解

前言:本篇内容主要讲解进程中系统调用fork和父子进程的概念与原理, 想要系统学习linux进程的友友们只管看本篇文章是不行的。 还要学习一些linux进程的周边知识以及linux进程其他方面的知识,博主的linux专栏中已经加入了这些文章方便友友们进…

连锁零售门店分析思路-人货场 数据分析

连锁零售门店分析思路 以下是一个连锁零售门店的分析思路: 一、市场与竞争分析 二、门店运营分析(销售分析) 三、销售与财务分析 四、客户分析 五、数字化与营销分析 最近帮一个大学生培训,就门店销售分析 ,说到门店…

记录些MySQL题集(8)

ACID原则、事务隔离级别及事务机制原理 一、事务的ACID原则 什么是事务呢?事务通常是由一个或一组SQL组成的,组成一个事务的SQL一般都是一个业务操作,例如聊到的下单:「扣库存数量、增加订单详情记录、插入物流信息」&#xff0…

Css布局-伸缩盒笔记

前言 伸缩盒作为css3中的布局标准,不得不学呀,跟着b站yu神走一遍,yushen牛逼! 伸缩盒子布局的优势 当然是伸缩了 伸缩容器与伸缩项目 display: flex display: inline-flex (用的少) 一个html元素既可以是…

我们距离通用人工智能还有多远?当它诞生后,会给社会发展带来哪些变革?

当我们谈论通用人工智能(AGI),我们指的是一种能够像人类一样执行各种认知任务的人工智能系统。目前,我们所拥有的人工智能技术主要是狭义人工智能(ANI),专注于特定任务,如语音识别、…

老司机减分宝典助手-学法减分扣分题目及答案 #经验分享#经验分享#职场发展

学法减分其实就是把我们驾驶证上面的分数一分一分地找回来,为什么说是一分一分地找回来呢?因为必须先把违章处理完才可以,无论这辆车是不是你的,无论这辆车挂靠在谁的公司名下或者是单位名下,你都可以把这个分找回来&a…

卷积神经网络图像识别车辆类型

卷积神经网络图像识别车辆类型 1、图像 自行车: 汽车: 摩托车: 2、数据集目录 3、流程 1、获取数据,把图像转成矩阵,并随机划分训练集、测试集 2、把标签转为数值,将标签向量转换为二值矩阵 3、图像数据归一化,0-1之间的值 4、构造卷积神经网络 5、设置图像输入…

3.RabbitMQ安装-Centos7

官方网址:gInstalling RabbitMQ | RabbitMQ 安装前提,需要一个erlang语言环境。 下载 erlang: Releases rabbitmq/erlang-rpm GitHub rabbitmq-server: 3.8.8 Releases rabbitmq/rabbitmq-server GitHub 安装命令 (说明i表示安装&#xff…

FPGA FIR fdatool filter designer MATLAB

位数问题 fdatool 先确定输入信号的位宽,比如17位在fdatool中,选set quantization parameters 选input/output 设置input word length 为17bit(not confirmed) fir compiler implementation 注意: 当设置输入位宽为16位时,ip核…

深入解析HNSW:Faiss中的层次化可导航小世界图

层次化可导航小世界(HNSW)图是向量相似性搜索中表现最佳的索引之一。HNSW 技术以其超级快速的搜索速度和出色的召回率,在近似最近邻(ANN)搜索中表现卓越。尽管 HNSW 是近似最近邻搜索中强大且受欢迎的算法,…

具有I2S输出的多模数字麦克风ICS-43434咪头

外观和丝印 ICS-43434麦克风3.50 mm x 2.65 mm,丝印为434(图片不好拍,隐约可见434) 一般描述 ICS-43434 是一款数字 IS 输出底部收音孔麦克风。完整的 ICS-43434 解决方案包括 MEMS 传感器、信号调理、模数转换器、抽取和抗混叠滤…

智能手术新时代:Apple Vision Pro在医疗领域的突破性应用

无人驾驶的未来:AI如何重塑我们的出行世界-CSDN博客文章浏览阅读2.2k次,点赞109次,收藏64次。无人驾驶汽车的发展是AI技术应用的一次伟大尝试。特斯拉与百度“萝卜快跑”在这个领域的竞争与合作,不仅展示了AI技术的强大潜力&#…

Heterophilous Distribution Propagation for Graph Neural Networks

推荐指数:2颗星 HDP不是聚集所有邻居信息,而是根据训练期间的伪标签自适应的将邻居分为同配和异配.并通过原型对比,垂直约束异配邻居分布 前人的问题 1.邻居划分的不足.已存在的方法要不不能区分同配和异配,要不简单的采用阈值去划分同配异配 2.以往的异配GNN仅仅是简单的邻居…

【C++】拷贝构造函数及析构函数

📢博客主页:https://blog.csdn.net/2301_779549673 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正! 📢本文由 JohnKi 原创,首发于 CSDN🙉 📢未来很长&#…

嵌入式Linux:文件属主和属组

目录 1、修改文件所有者和组 2、chown函数 3、fchown函数 4、lchown函数 在Linux系统中,每个文件都有一个属主(owner)和一个属组(group)。文件权限系统根据这些信息来决定哪些用户和组可以访问和操作文件。 文件属…

简单爬虫案例

准备工作: 1. 安装好python3 最低为3.6以上, 并成功运行pyhthon3 程序 2. 了解python 多进程原理 3. 了解 python HTTP 请求库 requests 的基本使用 4. 了解正则表达式的用法和python 中 re 库的基本使用 爬取目标 目标网站: https://…

【C++】类和对象的基本概念与使用

本文通过面向对象的概念以及通俗易懂的例子介绍面向对象引出类和对象。最后通过与之有相似之处的C语言中的struct一步步引出C中的类的定义方式,并提出了一些注意事项,最后描述了类的大小的计算方法。 一、什么是面向对象? 1.面向对象的概念 …