- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
前期工作
- 语言环境:Python3.9.18
- 编译器:Jupyter Lab
- 深度学习环境:Pytorch 1.12.1
1.设置GPU
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms,datasets
import os,PIL,random,pathlib
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device
2. 导入数据
import os,PIL,random,pathlib
data_dir = "F:/365data/P4/"
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[3] for path in data_paths]
classeNames
total_datadir = 'F:/365data/P4/'
train_transforms = 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(total_datadir,transform=train_transforms)
total_data
3.划分训练集测试集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
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
4.数据可视化
import matplotlib.pyplot as plt
from PIL import Image
image_folder = 'F:/365data/P4/Monkeypox/'
image_files = [f for f in os.listdir(image_folder) if f.endswith(('.jpg','.jpeg','.png'))]
fig,axes = plt.subplots(3,8,figsize=(16,6))
for ax,img_file in zip(axes.flat,image_files):
img_path = os.path.join(image_folder,img_file)
img = PIL.Image.open(img_path)
ax.imshow(img)
ax.axis('off')
plt.tight_layout()
plt.show()
二、构建ResNet-50模型
1.构造模型
import torch.nn.functional as F
# 构造ResNeXt50模型
class ResNeXtblock(nn.Module):
def __init__(self,in_channels,out_channels,stride=1,carinality=32):
super(ResNeXtblock,self).__init__()
D = out_channels*2
C = carinality
self.blockconv = nn.Sequential(
nn.Conv2d(in_channels,out_channels*2,kernel_size=1,stride=stride),
nn.BatchNorm2d(out_channels*2),
nn.ReLU(),
nn.Conv2d(out_channels*2,out_channels*2,kernel_size=3,stride=1,padding=1,groups=C),
nn.BatchNorm2d(out_channels*2),
nn.ReLU(),
nn.Conv2d(out_channels*2,out_channels*4,kernel_size=1,stride=1),
nn.BatchNorm2d(out_channels*4)
)
if stride !=1 or in_channels != out_channels*4:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels,out_channels*4,kernel_size=1,stride=stride),
nn.BatchNorm2d(out_channels*4)
)
def forward(self,x):
residual = x
out = self.blockconv(x)
if hasattr(self,'shortcut'):
residual = self.shortcut(x)
out += residual
out = F.relu(out)
return out
class ResNeXt50(nn.Module):
def __init__(self,block,num_classes=1000):
super(ResNeXt50,self).__init__()
self.conv1 = nn.Sequential(
nn.ZeroPad2d(3),
nn.Conv2d(3,64,kernel_size=7,stride=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d((3,3),stride=2)
)
self.in_channels = 64
self.layer1 = self.make_layer(ResNeXtblock,64,3,stride =1)
self.layer2 = self.make_layer(ResNeXtblock,128,4,stride=2) # 设置步长是为了减小特征图的尺寸,即宽高缩小一倍:1、捕捉到更大范围内的上下文信息2、有效减少模型参数数量和计算量,有助于控制模型复杂性和防止过拟合。
self.layer3 = self.make_layer(ResNeXtblock,256,6,stride=2)
self.layer4 = self.make_layer(ResNeXtblock,512,3,stride=2)
self.avgpool = nn.AvgPool2d((7,7))
self.fc = nn.Linear(512*4,num_classes)
def make_layer(self,block,channels,num_blocks,stride=1):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_channels,channels,stride))
self.in_channels = channels*4
return nn.Sequential(*layers)
def forward(self,x):
out = self.conv1(x)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.avgpool(out)
out = out.view(out.size(0),-1)
out = self.fc(out)
return out
import re
import torch.utils.model_zoo as model_zoo
from torchvision.models.resnet import model_urls
def resnet50(pretrained=False,**kwargs):
model = ResNeXt50(block=ResNeXtblock,num_classes=len(classeNames),**kwargs)
if pretrained:
state_dict = model_zoo.load_url(model_urls['resnet50'])
state_dict.pop('fc.weight')
state_dict.pop('fc.bias')
model.load_state_dict(state_dict,strict=False)
nn.init.kaiming_normal_(model.fc.weight)
nn.init.zeros_(model.fc.bias)
return model
model = resnet50(pretrained=False).to(device)
model
2. 统计模型参数
# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224))
----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
ZeroPad2d-1 [-1, 3, 230, 230] 0
Conv2d-2 [-1, 64, 112, 112] 9,472
BatchNorm2d-3 [-1, 64, 112, 112] 128
ReLU-4 [-1, 64, 112, 112] 0
MaxPool2d-5 [-1, 64, 55, 55] 0
Conv2d-6 [-1, 128, 55, 55] 8,320
BatchNorm2d-7 [-1, 128, 55, 55] 256
ReLU-8 [-1, 128, 55, 55] 0
Conv2d-9 [-1, 128, 55, 55] 4,736
BatchNorm2d-10 [-1, 128, 55, 55] 256
ReLU-11 [-1, 128, 55, 55] 0
Conv2d-12 [-1, 256, 55, 55] 33,024
BatchNorm2d-13 [-1, 256, 55, 55] 512
Conv2d-14 [-1, 256, 55, 55] 16,640
BatchNorm2d-15 [-1, 256, 55, 55] 512
ResNeXtblock-16 [-1, 256, 55, 55] 0
Conv2d-17 [-1, 128, 55, 55] 32,896
BatchNorm2d-18 [-1, 128, 55, 55] 256
ReLU-19 [-1, 128, 55, 55] 0
Conv2d-20 [-1, 128, 55, 55] 4,736
BatchNorm2d-21 [-1, 128, 55, 55] 256
ReLU-22 [-1, 128, 55, 55] 0
Conv2d-23 [-1, 256, 55, 55] 33,024
BatchNorm2d-24 [-1, 256, 55, 55] 512
ResNeXtblock-25 [-1, 256, 55, 55] 0
Conv2d-26 [-1, 128, 55, 55] 32,896
BatchNorm2d-27 [-1, 128, 55, 55] 256
ReLU-28 [-1, 128, 55, 55] 0
Conv2d-29 [-1, 128, 55, 55] 4,736
BatchNorm2d-30 [-1, 128, 55, 55] 256
ReLU-31 [-1, 128, 55, 55] 0
Conv2d-32 [-1, 256, 55, 55] 33,024
BatchNorm2d-33 [-1, 256, 55, 55] 512
ResNeXtblock-34 [-1, 256, 55, 55] 0
Conv2d-35 [-1, 256, 28, 28] 65,792
BatchNorm2d-36 [-1, 256, 28, 28] 512
ReLU-37 [-1, 256, 28, 28] 0
Conv2d-38 [-1, 256, 28, 28] 18,688
BatchNorm2d-39 [-1, 256, 28, 28] 512
ReLU-40 [-1, 256, 28, 28] 0
Conv2d-41 [-1, 512, 28, 28] 131,584
BatchNorm2d-42 [-1, 512, 28, 28] 1,024
Conv2d-43 [-1, 512, 28, 28] 131,584
BatchNorm2d-44 [-1, 512, 28, 28] 1,024
ResNeXtblock-45 [-1, 512, 28, 28] 0
Conv2d-46 [-1, 256, 28, 28] 131,328
BatchNorm2d-47 [-1, 256, 28, 28] 512
ReLU-48 [-1, 256, 28, 28] 0
Conv2d-49 [-1, 256, 28, 28] 18,688
BatchNorm2d-50 [-1, 256, 28, 28] 512
ReLU-51 [-1, 256, 28, 28] 0
Conv2d-52 [-1, 512, 28, 28] 131,584
BatchNorm2d-53 [-1, 512, 28, 28] 1,024
ResNeXtblock-54 [-1, 512, 28, 28] 0
Conv2d-55 [-1, 256, 28, 28] 131,328
BatchNorm2d-56 [-1, 256, 28, 28] 512
ReLU-57 [-1, 256, 28, 28] 0
Conv2d-58 [-1, 256, 28, 28] 18,688
BatchNorm2d-59 [-1, 256, 28, 28] 512
ReLU-60 [-1, 256, 28, 28] 0
Conv2d-61 [-1, 512, 28, 28] 131,584
BatchNorm2d-62 [-1, 512, 28, 28] 1,024
ResNeXtblock-63 [-1, 512, 28, 28] 0
Conv2d-64 [-1, 256, 28, 28] 131,328
BatchNorm2d-65 [-1, 256, 28, 28] 512
ReLU-66 [-1, 256, 28, 28] 0
Conv2d-67 [-1, 256, 28, 28] 18,688
BatchNorm2d-68 [-1, 256, 28, 28] 512
ReLU-69 [-1, 256, 28, 28] 0
Conv2d-70 [-1, 512, 28, 28] 131,584
BatchNorm2d-71 [-1, 512, 28, 28] 1,024
ResNeXtblock-72 [-1, 512, 28, 28] 0
Conv2d-73 [-1, 512, 14, 14] 262,656
BatchNorm2d-74 [-1, 512, 14, 14] 1,024
ReLU-75 [-1, 512, 14, 14] 0
Conv2d-76 [-1, 512, 14, 14] 74,240
BatchNorm2d-77 [-1, 512, 14, 14] 1,024
ReLU-78 [-1, 512, 14, 14] 0
Conv2d-79 [-1, 1024, 14, 14] 525,312
BatchNorm2d-80 [-1, 1024, 14, 14] 2,048
Conv2d-81 [-1, 1024, 14, 14] 525,312
BatchNorm2d-82 [-1, 1024, 14, 14] 2,048
ResNeXtblock-83 [-1, 1024, 14, 14] 0
Conv2d-84 [-1, 512, 14, 14] 524,800
BatchNorm2d-85 [-1, 512, 14, 14] 1,024
ReLU-86 [-1, 512, 14, 14] 0
Conv2d-87 [-1, 512, 14, 14] 74,240
BatchNorm2d-88 [-1, 512, 14, 14] 1,024
ReLU-89 [-1, 512, 14, 14] 0
Conv2d-90 [-1, 1024, 14, 14] 525,312
BatchNorm2d-91 [-1, 1024, 14, 14] 2,048
ResNeXtblock-92 [-1, 1024, 14, 14] 0
Conv2d-93 [-1, 512, 14, 14] 524,800
BatchNorm2d-94 [-1, 512, 14, 14] 1,024
ReLU-95 [-1, 512, 14, 14] 0
Conv2d-96 [-1, 512, 14, 14] 74,240
BatchNorm2d-97 [-1, 512, 14, 14] 1,024
ReLU-98 [-1, 512, 14, 14] 0
Conv2d-99 [-1, 1024, 14, 14] 525,312
BatchNorm2d-100 [-1, 1024, 14, 14] 2,048
ResNeXtblock-101 [-1, 1024, 14, 14] 0
Conv2d-102 [-1, 512, 14, 14] 524,800
BatchNorm2d-103 [-1, 512, 14, 14] 1,024
ReLU-104 [-1, 512, 14, 14] 0
Conv2d-105 [-1, 512, 14, 14] 74,240
BatchNorm2d-106 [-1, 512, 14, 14] 1,024
ReLU-107 [-1, 512, 14, 14] 0
Conv2d-108 [-1, 1024, 14, 14] 525,312
BatchNorm2d-109 [-1, 1024, 14, 14] 2,048
ResNeXtblock-110 [-1, 1024, 14, 14] 0
Conv2d-111 [-1, 512, 14, 14] 524,800
BatchNorm2d-112 [-1, 512, 14, 14] 1,024
ReLU-113 [-1, 512, 14, 14] 0
Conv2d-114 [-1, 512, 14, 14] 74,240
BatchNorm2d-115 [-1, 512, 14, 14] 1,024
ReLU-116 [-1, 512, 14, 14] 0
Conv2d-117 [-1, 1024, 14, 14] 525,312
BatchNorm2d-118 [-1, 1024, 14, 14] 2,048
ResNeXtblock-119 [-1, 1024, 14, 14] 0
Conv2d-120 [-1, 512, 14, 14] 524,800
BatchNorm2d-121 [-1, 512, 14, 14] 1,024
ReLU-122 [-1, 512, 14, 14] 0
Conv2d-123 [-1, 512, 14, 14] 74,240
BatchNorm2d-124 [-1, 512, 14, 14] 1,024
ReLU-125 [-1, 512, 14, 14] 0
Conv2d-126 [-1, 1024, 14, 14] 525,312
BatchNorm2d-127 [-1, 1024, 14, 14] 2,048
ResNeXtblock-128 [-1, 1024, 14, 14] 0
Conv2d-129 [-1, 1024, 7, 7] 1,049,600
BatchNorm2d-130 [-1, 1024, 7, 7] 2,048
ReLU-131 [-1, 1024, 7, 7] 0
Conv2d-132 [-1, 1024, 7, 7] 295,936
BatchNorm2d-133 [-1, 1024, 7, 7] 2,048
ReLU-134 [-1, 1024, 7, 7] 0
Conv2d-135 [-1, 2048, 7, 7] 2,099,200
BatchNorm2d-136 [-1, 2048, 7, 7] 4,096
Conv2d-137 [-1, 2048, 7, 7] 2,099,200
BatchNorm2d-138 [-1, 2048, 7, 7] 4,096
ResNeXtblock-139 [-1, 2048, 7, 7] 0
Conv2d-140 [-1, 1024, 7, 7] 2,098,176
BatchNorm2d-141 [-1, 1024, 7, 7] 2,048
ReLU-142 [-1, 1024, 7, 7] 0
Conv2d-143 [-1, 1024, 7, 7] 295,936
BatchNorm2d-144 [-1, 1024, 7, 7] 2,048
ReLU-145 [-1, 1024, 7, 7] 0
Conv2d-146 [-1, 2048, 7, 7] 2,099,200
BatchNorm2d-147 [-1, 2048, 7, 7] 4,096
ResNeXtblock-148 [-1, 2048, 7, 7] 0
Conv2d-149 [-1, 1024, 7, 7] 2,098,176
BatchNorm2d-150 [-1, 1024, 7, 7] 2,048
ReLU-151 [-1, 1024, 7, 7] 0
Conv2d-152 [-1, 1024, 7, 7] 295,936
BatchNorm2d-153 [-1, 1024, 7, 7] 2,048
ReLU-154 [-1, 1024, 7, 7] 0
Conv2d-155 [-1, 2048, 7, 7] 2,099,200
BatchNorm2d-156 [-1, 2048, 7, 7] 4,096
ResNeXtblock-157 [-1, 2048, 7, 7] 0
AvgPool2d-158 [-1, 2048, 1, 1] 0
Linear-159 [-1, 2] 4,098
================================================================
Total params: 23,018,114
Trainable params: 23,018,114
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 292.37
Params size (MB): 87.81
Estimated Total Size (MB): 380.75
----------------------------------------------------------------
三、训练模型
1. 构建训练函数
def train(dataloader,model,optimizer,loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
train_acc,train_loss = 0,0
for 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_loss += loss.item()
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss /= num_batches
train_acc /= size
return train_acc,train_loss
2. 构建测试函数
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小
num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)
test_loss, test_acc = 0, 0
# 当不进行训练时,停止梯度更新,节省计算内存消耗
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
3. 优化器和学习率
loss_fn = nn.CrossEntropyLoss()
learn_rate = 1e-4
opt = torch.optim.Adam(model.parameters(),lr=learn_rate)
import copy
epochs = 20
train_loss=[]
train_acc=[]
test_loss=[]
test_acc=[]
best_acc = 0
for epoch in range(epochs):
model.train()
epoch_train_acc,epoch_train_loss = train(train_dl,model,opt,loss_fn)
model.eval()
epoch_test_acc,epoch_test_loss = test(test_dl,model,loss_fn)
if epoch_test_acc > best_acc:
best_acc = epoch_test_acc
best_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 = opt.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 = 'F:/365data/J6best_model.pth' # 保存的参数文件名
torch.save(best_model.state_dict(), PATH)
print('Done')
Epoch: 1, Train_acc:56.2%, Train_loss:0.757, Test_acc:66.9%, Test_loss:0.586, Lr:1.00E-04
Epoch: 2, Train_acc:68.0%, Train_loss:0.602, Test_acc:67.8%, Test_loss:0.723, Lr:1.00E-04
Epoch: 3, Train_acc:71.7%, Train_loss:0.558, Test_acc:61.1%, Test_loss:0.745, Lr:1.00E-04
Epoch: 4, Train_acc:70.3%, Train_loss:0.572, Test_acc:73.4%, Test_loss:0.544, Lr:1.00E-04
Epoch: 5, Train_acc:76.1%, Train_loss:0.506, Test_acc:76.5%, Test_loss:0.513, Lr:1.00E-04
Epoch: 6, Train_acc:79.2%, Train_loss:0.464, Test_acc:75.8%, Test_loss:0.527, Lr:1.00E-04
Epoch: 7, Train_acc:79.3%, Train_loss:0.449, Test_acc:72.0%, Test_loss:0.588, Lr:1.00E-04
Epoch: 8, Train_acc:81.0%, Train_loss:0.431, Test_acc:73.4%, Test_loss:0.800, Lr:1.00E-04
Epoch: 9, Train_acc:84.9%, Train_loss:0.348, Test_acc:82.8%, Test_loss:0.402, Lr:1.00E-04
Epoch:10, Train_acc:86.6%, Train_loss:0.311, Test_acc:80.0%, Test_loss:0.503, Lr:1.00E-04
Epoch:11, Train_acc:88.7%, Train_loss:0.272, Test_acc:80.0%, Test_loss:0.562, Lr:1.00E-04
Epoch:12, Train_acc:88.5%, Train_loss:0.283, Test_acc:80.7%, Test_loss:0.517, Lr:1.00E-04
Epoch:13, Train_acc:90.0%, Train_loss:0.234, Test_acc:86.0%, Test_loss:0.396, Lr:1.00E-04
Epoch:14, Train_acc:90.4%, Train_loss:0.226, Test_acc:80.4%, Test_loss:0.462, Lr:1.00E-04
Epoch:15, Train_acc:92.9%, Train_loss:0.169, Test_acc:84.1%, Test_loss:0.452, Lr:1.00E-04
Epoch:16, Train_acc:94.0%, Train_loss:0.153, Test_acc:81.8%, Test_loss:0.490, Lr:1.00E-04
Epoch:17, Train_acc:94.9%, Train_loss:0.131, Test_acc:84.1%, Test_loss:0.465, Lr:1.00E-04
Epoch:18, Train_acc:93.8%, Train_loss:0.157, Test_acc:83.2%, Test_loss:0.455, Lr:1.00E-04
Epoch:19, Train_acc:94.3%, Train_loss:0.154, Test_acc:80.9%, Test_loss:0.560, Lr:1.00E-04
Epoch:20, Train_acc:94.7%, Train_loss:0.141, Test_acc:84.8%, Test_loss:0.429, Lr:1.00E-04
Done
5. 模型评估
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()
总结
- 我将原tensorflow代码改完了pytorch代码
- 本节使用了分组卷积方法,在pytorch中,在nn.Conv2d()中使用参数groups可以很容易实现分组卷积方法