一、前期准备
1.设置GPU
import torch from torch import nn import torchvision from torchvision import transforms,datasets,models import matplotlib.pyplot as plt import os,PIL,pathlib
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device
device(type='cuda')
2.导入数据
data_dir = './houdou/' data_dir = pathlib.Path(data_dir) data_paths = list(data_dir.glob('*')) classNames = [str(path).split('\\')[1] for path in data_paths] classNames
train_transforms = transforms.Compose([ transforms.Resize([224,224]),# resize输入图片 transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换成tensor transforms.Normalize( mean = [0.485, 0.456, 0.406], std = [0.229,0.224,0.225]) # 从数据集中随机抽样计算得到 ]) total_data = datasets.ImageFolder(data_dir,transform=train_transforms) total_data
Dataset ImageFolder Number of datapoints: 2142 Root location: houdou StandardTransform Transform: Compose( Resize(size=[224, 224], interpolation=PIL.Image.BILINEAR) ToTensor() Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) )
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_size,test_size
(1713, 429)
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)
4.数据可视化
imgs, labels = next(iter(train_dl)) imgs.shape
torch.Size([32, 3, 224, 224])
import numpy as np # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch) plt.figure(figsize=(20, 5)) for i, imgs in enumerate(imgs[:20]): npimg = imgs.numpy().transpose((1,2,0)) npimg = npimg * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406)) npimg = npimg.clip(0, 1) # 将整个figure分成2行10列,绘制第i+1个子图。 plt.subplot(2, 10, i+1) plt.imshow(npimg) plt.axis('off')
for X,y in test_dl: print('Shape of X [N, C, H, W]:', X.shape) print('Shape of y:', y.shape) break
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32])
二、构建简单的CNN网络
# import torch.nn.functional as F # num_classes = 4 # 图片的类别数 # class Network_bn(nn.Module): # def __init__(self): # super().__init__() # # 特征提取网络 # self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0) # self.bn1 = nn.BatchNorm2d(12) # self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0) # self.bn2 = nn.BatchNorm2d(12) # self.pool = nn.MaxPool2d(2,2) # self.conv3 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0) # self.bn3 = nn.BatchNorm2d(24) # self.conv4 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0) # self.bn4 = nn.BatchNorm2d(24) # # 分类网络 # self.fc1 = nn.Linear(24*50*50,num_classes) # # 前向传播 # def forward(self, x): # x = F.relu(self.bn1(self.conv1(x))) # x = F.relu(self.bn2(self.conv2(x))) # x = self.pool(x) # x = F.relu(self.bn3(self.conv3(x))) # x = F.relu(self.bn4(self.conv4(x))) # x = self.pool(x) # x = x.view(-1,24*50*50) # x = self.fc1(x) # return x # model = Network_bn().to(device) # model
2.1 迁移学习
2.1.1 调用resnet18预训练模型、冻结参数
feature_extract = True # 冻结参数 def set_parameter_requires_grad(model, feature_extracting): if feature_extracting: for param in model.parameters(): param.requires_grad = False # 修改输出层 def initialize_model(num_classes, feature_extract, use_pretrained=True): model_ft = models.resnet18(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, num_classes) input_size = 32 return model_ft, input_size
model_ft, input_size = initialize_model(2, feature_extract, use_pretrained=True) model_ft = model_ft.to(device) model_ft
略
2.1.2 取出输出层参数
取出输出层参数 后面用于训练更新
# 设置训练哪些层 params_to_update = model_ft.parameters() print("Params to learn:") if feature_extract: # 自己只训练输出层 params_to_update = [] for name,param in model_ft.named_parameters(): if param.requires_grad == True: params_to_update.append(param) print("\t",name) else: for name,param in model_ft.named_parameters(): if param.requires_grad == True: print("\t",name)
Params to learn:
fc.weight
fc.bias
三、训练模型
3.1 设置超参数
动态学习率
# 优化器设置 optimizer = torch.optim.Adam(params_to_update, lr=1e-4)#要训练啥参数,你来定 scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.92)#学习率每7个epoch衰减成原来的1/10 loss_fn = nn.CrossEntropyLoss()
# def adjust_learning_rate(optimizer, epoch, start_lr): # # 每2个 epoch衰减到原来的0.98 # lr = start_lr * (0.92 ** (epoch //2)) # for param_group in optimizer.param_groups: # param_group['lr'] = lr # optimizer = torch.optim.Adam(params_to_update,lr=1e-4)
3.2 编写训练函数
# 训练循环 def train(dataloader, model, loss_fn, optimizer): size = len(dataloader.dataset) # 训练集的大小,一共900张图片 num_batches = len(dataloader) # 批次数目,29(900/32) train_loss, train_acc = 0, 0 # 初始化训练损失和正确率 for X, y in dataloader: # 获取图片及其标签 X, y = X.to(device), y.to(device) # 计算预测误差 pred = model(X) # 网络输出 loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失 # 反向传播 optimizer.zero_grad() # grad属性归零 loss.backward() # 反向传播 optimizer.step() # 每一步自动更新 # 记录acc与loss train_acc += (pred.argmax(1) == y).type(torch.float).sum().item() train_loss += loss.item() train_acc /= size train_loss /= num_batches return train_acc, train_loss
3.3 编写测试函数
def test (dataloader, model, loss_fn): size = len(dataloader.dataset) # 测试集的大小,一共10000张图片 num_batches = len(dataloader) # 批次数目,8(255/32=8,向上取整) 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.4 正式训练
3.4.1 训练输出层
epochs = 20 train_loss = [] train_acc = [] test_loss = [] test_acc = [] best_acc = 0 filename='checkpoint.pth' for epoch in range(epochs): model_ft.train() epoch_train_acc, epoch_train_loss = train(train_dl, model_ft, loss_fn, optimizer) scheduler.step()#学习率衰减 model_ft.eval() epoch_test_acc, epoch_test_loss = test(test_dl, model_ft, loss_fn) # 保存最优模型 if epoch_test_acc > best_acc: best_acc = epoch_test_acc state = { 'state_dict': model_ft.state_dict(),#字典里key就是各层的名字,值就是训练好的权重 'best_acc': best_acc, 'optimizer' : optimizer.state_dict(), } torch.save(state, filename) train_acc.append(epoch_train_acc) train_loss.append(epoch_train_loss) test_acc.append(epoch_test_acc) test_loss.append(epoch_test_loss) template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}') print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss)) print('Done') print('best_acc:',best_acc)
Epoch: 1, Train_acc:54.6%, Train_loss:0.707, Test_acc:54.8%,Test_loss:0.677
Epoch: 2, Train_acc:61.2%, Train_loss:0.648, Test_acc:64.8%,Test_loss:0.637
Epoch: 3, Train_acc:67.3%, Train_loss:0.615, Test_acc:67.8%,Test_loss:0.603
Epoch: 4, Train_acc:70.5%, Train_loss:0.589, Test_acc:72.5%,Test_loss:0.583
Epoch: 5, Train_acc:73.6%, Train_loss:0.567, Test_acc:75.8%,Test_loss:0.554
Epoch: 6, Train_acc:75.0%, Train_loss:0.544, Test_acc:77.2%,Test_loss:0.561
Epoch: 7, Train_acc:76.7%, Train_loss:0.530, Test_acc:80.0%,Test_loss:0.528
Epoch: 8, Train_acc:78.4%, Train_loss:0.517, Test_acc:80.4%,Test_loss:0.510
Epoch: 9, Train_acc:78.5%, Train_loss:0.503, Test_acc:80.0%,Test_loss:0.503
Epoch:10, Train_acc:78.8%, Train_loss:0.499, Test_acc:81.6%,Test_loss:0.492
Epoch:11, Train_acc:80.2%, Train_loss:0.488, Test_acc:81.8%,Test_loss:0.477
Epoch:12, Train_acc:79.7%, Train_loss:0.478, Test_acc:81.1%,Test_loss:0.477
Epoch:13, Train_acc:81.7%, Train_loss:0.471, Test_acc:82.1%,Test_loss:0.468
Epoch:14, Train_acc:81.4%, Train_loss:0.460, Test_acc:82.8%,Test_loss:0.462
Epoch:15, Train_acc:81.7%, Train_loss:0.459, Test_acc:82.8%,Test_loss:0.454
Epoch:16, Train_acc:81.3%, Train_loss:0.455, Test_acc:82.8%,Test_loss:0.440
Epoch:17, Train_acc:82.7%, Train_loss:0.447, Test_acc:83.7%,Test_loss:0.440
Epoch:18, Train_acc:82.2%, Train_loss:0.449, Test_acc:82.1%,Test_loss:0.435
Epoch:19, Train_acc:83.1%, Train_loss:0.433, Test_acc:83.2%,Test_loss:0.439
Epoch:20, Train_acc:82.9%, Train_loss:0.432, Test_acc:82.5%,Test_loss:0.430
Done
3.4.2 训练所有层
for param in model_ft.parameters(): param.requires_grad = True # 再继续训练所有的参数,学习率调小一点 optimizer = torch.optim.Adam(model_ft.parameters(), lr=1e-4) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.92) # 损失函数 criterion = nn.CrossEntropyLoss()
# 加载之前训练好的权重参数 checkpoint = torch.load(filename) best_acc = checkpoint['best_acc'] model_ft.load_state_dict(checkpoint['state_dict'])
epochs = 20 train_loss = [] train_acc = [] test_loss = [] test_acc = [] best_acc = 0 filename='best.pth' for epoch in range(epochs): model_ft.train() epoch_train_acc, epoch_train_loss = train(train_dl, model_ft, loss_fn, optimizer) scheduler.step()#学习率衰减 model_ft.eval() epoch_test_acc, epoch_test_loss = test(test_dl, model_ft, loss_fn) # 保存最优模型 if epoch_test_acc > best_acc: best_acc = epoch_test_acc state = { 'state_dict': model_ft.state_dict(),#字典里key就是各层的名字,值就是训练好的权重 'best_acc': best_acc, 'optimizer' : optimizer.state_dict(), } torch.save(state, filename) train_acc.append(epoch_train_acc) train_loss.append(epoch_train_loss) test_acc.append(epoch_test_acc) test_loss.append(epoch_test_loss) template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}') print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss)) print('Done') print('best_acc:',best_acc)
Epoch: 1, Train_acc:90.7%, Train_loss:0.229, Test_acc:93.0%,Test_loss:0.171
Epoch: 2, Train_acc:97.7%, Train_loss:0.067, Test_acc:96.7%,Test_loss:0.097
Epoch: 3, Train_acc:98.1%, Train_loss:0.052, Test_acc:95.3%,Test_loss:0.142
Epoch: 4, Train_acc:99.4%, Train_loss:0.024, Test_acc:97.0%,Test_loss:0.078
Epoch: 5, Train_acc:99.2%, Train_loss:0.026, Test_acc:97.4%,Test_loss:0.077
Epoch: 6, Train_acc:99.8%, Train_loss:0.009, Test_acc:97.2%,Test_loss:0.085
Epoch: 7, Train_acc:99.7%, Train_loss:0.014, Test_acc:97.0%,Test_loss:0.114
Epoch: 8, Train_acc:99.8%, Train_loss:0.006, Test_acc:97.4%,Test_loss:0.070
Epoch: 9, Train_acc:99.6%, Train_loss:0.011, Test_acc:97.4%,Test_loss:0.080
Epoch:10, Train_acc:99.5%, Train_loss:0.014, Test_acc:95.3%,Test_loss:0.145
Epoch:11, Train_acc:99.6%, Train_loss:0.012, Test_acc:95.8%,Test_loss:0.145
Epoch:12, Train_acc:99.6%, Train_loss:0.010, Test_acc:97.2%,Test_loss:0.081
Epoch:13, Train_acc:99.8%, Train_loss:0.008, Test_acc:96.3%,Test_loss:0.131
Epoch:14, Train_acc:99.8%, Train_loss:0.005, Test_acc:96.0%,Test_loss:0.106
Epoch:15, Train_acc:100.0%, Train_loss:0.002, Test_acc:96.5%,Test_loss:0.099
Epoch:16, Train_acc:99.9%, Train_loss:0.002, Test_acc:96.3%,Test_loss:0.105
Epoch:17, Train_acc:100.0%, Train_loss:0.001, Test_acc:97.0%,Test_loss:0.085
Epoch:18, Train_acc:100.0%, Train_loss:0.001, Test_acc:96.7%,Test_loss:0.105
Epoch:19, Train_acc:100.0%, Train_loss:0.001, Test_acc:97.0%,Test_loss:0.097
Epoch:20, Train_acc:99.9%, Train_loss:0.002, Test_acc:97.4%,Test_loss:0.077
Done
四、结果可视化
加载训练好的模型
model_ft, input_size = initialize_model(2, feature_extract, use_pretrained=True) # GPU模式 model_ft = model_ft.to(device) # 保存文件的名字 filename='best.pth' # 加载模型 checkpoint = torch.load(filename) best_acc = checkpoint['best_acc'] model_ft.load_state_dict(checkpoint['state_dict'])
结果可视化
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()
测试模型
train_on_gpu = True # 得到一个batch的测试数据 imgs, labels = next(iter(train_dl)) # 进行预测 model_ft.eval() if train_on_gpu: output = model_ft(imgs.cuda()) else: output = model_ft(imgs) # 获得预测结果(概率最大的) _, preds_tensor = torch.max(output, 1) preds = np.squeeze(preds_tensor.numpy()) if not train_on_gpu else np.squeeze(preds_tensor.cpu().numpy()) preds
array([1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0,
0, 1, 1, 0, 1, 0, 0, 1, 0, 0], dtype=int64)
import numpy as np # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch) plt.figure(figsize=(20, 10)) for idx, imgs in enumerate(imgs[:10]): #ax = fig.add_subplot(rows, columns, idx+1, xticks=[], yticks=[]) npimg = imgs.numpy().transpose((1,2,0)) npimg = npimg * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406)) npimg = npimg.clip(0, 1) # 将整个figure分成2行10列,绘制第i+1个子图。 ax = plt.subplot(2, 5, idx+1) ax.set_title("{} ({})".format(classNames[preds[idx]], classNames[labels[idx]]), color=("green" if classNames[preds[idx]]==classNames[labels[idx]] else "red")) plt.imshow(npimg) plt.axis('off')