5、运动鞋识别

 

学习要求

  • 了解如何设置动态学习率(重点)
  • 调整代码使测试集accuracy到达84%。

学习提高

  • 保存训练过程中的最佳模型权重
  • 调整代码使测试集accuracy到达86%。

一、前期工作准备部分

1、设置GPU

In [1]:
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
from sklearn.model_selection import KFold
from torch.optim.lr_scheduler import StepLR, MultiStepLR, LambdaLR, ExponentialLR, CosineAnnealingLR, ReduceLROnPlateau

import os,PIL,pathlib,random

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

device
Out[1]:
device(type='cuda')
 

2、导入数据

In [2]:
data_dir = '../data/5-data'
# 通过Path类创建路径对象
data_dir = pathlib.Path(data_dir)
# 获取路径下所有文件路径
paths= list(data_dir.glob('*'))
# 获取所有文件夹的名字,也就是图片类别
classname = [str(path).split("\\")[3] for path in paths]
print(classname)

# 图像transforms
# 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
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和std是从数据中随机抽样计算得到的,其实这个数值是pytorch上给的通用的统计值
])
test_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和std是从数据中随机抽样计算得到的,其实这个数值是pytorch上给的通用的统计值
])
train_dataset = datasets.ImageFolder("../data/5-data/train/",transform=train_transforms)
test_dataset = datasets.ImageFolder("../data/5-data/test//",transform=train_transforms)
 
['test', 'train']
In [3]:
train_dataset.class_to_idx
Out[3]:
{'adidas': 0, 'nike': 1}
In [4]:
batch_size = 32

train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size=batch_size,
                                       shuffle=True,
                                       num_workers=3)

test_dl = torch.utils.data.DataLoader(test_dataset,
                                      batch_size=batch_size,
                                      shuffle=True,
                                      num_workers=3)
In [5]:
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
 

二、构建简单的CNN网络

对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

In [6]:
import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
        self.conv1=nn.Sequential(
            nn.Conv2d(3, 12, kernel_size=5, padding=0), # 12*220*220
            nn.BatchNorm2d(12),
            nn.ReLU())
        
        self.conv2=nn.Sequential(
            nn.Conv2d(12, 12, kernel_size=5, padding=0), # 12*216*216
            nn.BatchNorm2d(12),
            nn.ReLU())
        
        self.pool3=nn.Sequential(
            nn.MaxPool2d(2))                              # 12*108*108
        
        self.conv4=nn.Sequential(
            nn.Conv2d(12, 24, kernel_size=5, padding=0), # 24*104*104
            nn.BatchNorm2d(24),
            nn.ReLU())
        
        self.conv5=nn.Sequential(
            nn.Conv2d(24, 24, kernel_size=5, padding=0), # 24*100*100
            nn.BatchNorm2d(24),
            nn.ReLU())
        
        self.pool6=nn.Sequential(
            nn.MaxPool2d(2))                              # 24*50*50

        self.dropout = nn.Sequential(
            nn.Dropout(0.2))
        
        self.fc=nn.Sequential(
            nn.Linear(24*50*50, len(classname))) # K同学这总是写错

    def forward(self, x):
        batch_size = x.size(0)
        x = self.conv1(x)  # 卷积-BN-激活
        x = self.conv2(x)  # 卷积-BN-激活
        x = self.pool3(x)  # 池化
        x = self.conv4(x)  # 卷积-BN-激活
        x = self.conv5(x)  # 卷积-BN-激活
        x = self.pool6(x)  # 池化
        x = self.dropout(x)
        x = x.view(batch_size, -1)  # flatten 变成全连接网络需要的输入 (batch, 24*50*50) ==> (batch, -1), -1 此处自动算出的是24*50*50
        x = self.fc(x)

        return x

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
model
 
Using cuda device
Out[6]:
Network_bn(
  (conv1): Sequential(
    (0): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv2): Sequential(
    (0): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool3): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv4): Sequential(
    (0): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv5): Sequential(
    (0): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool6): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (dropout): Sequential(
    (0): Dropout(p=0.2, inplace=False)
  )
  (fc): Sequential(
    (0): Linear(in_features=60000, out_features=2, bias=True)
  )
)
 

建立更好的CNN网络模型:加深、dropout与adam、lr_decay

第一次调参:

首先尝试将kernel_size调整为3,其次由于样本量并不大,考虑将dropout调大成0.5。但是由于一下子调整的好像有点狠,同样40个epoch难以很好的学习模型。

第二次调参:

本次针对epoch可能不太够选择了提高学习率,同时删去学习率衰减机制。虽然前期仅20余个epoch就让train_loss低于0.3,但是test_loss却一直卡住降不下去。后面试图通过恢复学习率衰减,但是并不能对test_loss产生很好的效果,反而让train的更快拟合完成。

第三次调参:

尝试使用AvgPool2d进行池化操作,但是不仅test_loss不好,连train_loss都进行的并不好。

第四次调参:

增加一层的dropout在第一次pooling之后,同时将学习率增大到1e-3,最终成功的在测试集上普遍达到了80%的准确率。

第五次调参:

调用Adam优化器进行优化,终于有最佳test_acc提升到86%以上,大量test_acc普遍在84%以上

Epoch:24, Train_acc:98.8%, Train_loss:0.046, Test_acc:85.5%, Test_loss:0.616, Lr:8.01E-04

第六次调参:

参照别人的博客文章,运动鞋识别-第五周

  • 将第一个dropout删去。
  • 将动态学习率调整为每10个epoch衰减为原来的0.98
  • 继续使用Adam优化器

但是对于我的模型效果并不好,因此还是采取原来第五次调参的结果。

In [18]:
import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
        self.conv1=nn.Sequential(
            nn.Conv2d(3, 12, kernel_size=3, padding=0), # 12*222*222
            nn.BatchNorm2d(12),
            nn.ReLU())
        
        self.conv2=nn.Sequential(
            nn.Conv2d(12, 12, kernel_size=3, padding=0), # 12*220*220
            nn.BatchNorm2d(12),
            nn.ReLU())
        
        self.pool3=nn.Sequential(
            nn.MaxPool2d(2))                              # 12*110*110
        
        self.dropout1 = nn.Sequential(
            nn.Dropout(0.5))
        
        self.conv4=nn.Sequential(
            nn.Conv2d(12, 24, kernel_size=3, padding=0), # 24*108*108
            nn.BatchNorm2d(24),
            nn.ReLU())
        
        self.conv5=nn.Sequential(
            nn.Conv2d(24, 24, kernel_size=3, padding=0), # 24*106*106
            nn.BatchNorm2d(24),
            nn.ReLU())
        
        self.pool6=nn.Sequential(
            nn.MaxPool2d(2))                              # 24*53*53

        self.dropout2 = nn.Sequential(
            nn.Dropout(0.5))
        
        self.fc=nn.Sequential(
            nn.Linear(24*53*53, len(classname))) # K同学这总是写错

    def forward(self, x):
        batch_size = x.size(0)
        x = self.conv1(x)  # 卷积-BN-激活
        x = self.conv2(x)  # 卷积-BN-激活
        x = self.pool3(x)  # 池化
        x = self.dropout1(x)
        x = self.conv4(x)  # 卷积-BN-激活
        x = self.conv5(x)  # 卷积-BN-激活
        x = self.pool6(x)  # 池化
        x = self.dropout2(x)
        x = x.view(batch_size, -1)  # flatten 变成全连接网络需要的输入 (batch, 24*50*50) ==> (batch, -1), -1 此处自动算出的是24*50*50
        x = self.fc(x)

        return x

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
model
 
Using cuda device
Out[18]:
Network_bn(
  (conv1): Sequential(
    (0): Conv2d(3, 12, kernel_size=(3, 3), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv2): Sequential(
    (0): Conv2d(12, 12, kernel_size=(3, 3), stride=(1, 1))
    (1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool3): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (dropout1): Sequential(
    (0): Dropout(p=0.5, inplace=False)
  )
  (conv4): Sequential(
    (0): Conv2d(12, 24, kernel_size=(3, 3), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (conv5): Sequential(
    (0): Conv2d(24, 24, kernel_size=(3, 3), stride=(1, 1))
    (1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
  )
  (pool6): Sequential(
    (0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (dropout2): Sequential(
    (0): Dropout(p=0.5, inplace=False)
  )
  (fc): Sequential(
    (0): Linear(in_features=67416, out_features=2, bias=True)
  )
)
 

三、 训练模型

1、设置超参数

In [22]:
def adjust_learning_rate(optimizer, epoch, start_lr):
    # 每 2 个epoch衰减到原来的 0.98
    lr = start_lr * (0.98 ** (epoch // 2))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

learn_rate = 1e-3 # 初始学习率
optimizer  = torch.optim.Adam(model.parameters(), lr=learn_rate, weight_decay = 0.01)
 

2、编写训练函数

In [9]:
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小
    num_batches = len(dataloader)   # 批次数目,1875(60000/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、编写测试函数

In [10]:
def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,31310000/32=312.5,向上取整)
    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
 

4、正式训练

In [23]:
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
epochs     = 50

train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

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)
    
    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))
print('Done')
 
Epoch: 1, Train_acc:76.1%, Train_loss:2.354, Test_acc:72.4%, Test_loss:2.095, Lr:1.00E-03
Epoch: 2, Train_acc:89.0%, Train_loss:0.561, Test_acc:75.0%, Test_loss:1.335, Lr:1.00E-03
Epoch: 3, Train_acc:93.8%, Train_loss:0.231, Test_acc:76.3%, Test_loss:1.537, Lr:9.80E-04
Epoch: 4, Train_acc:95.4%, Train_loss:0.148, Test_acc:73.7%, Test_loss:1.565, Lr:9.80E-04
Epoch: 5, Train_acc:95.8%, Train_loss:0.111, Test_acc:76.3%, Test_loss:1.382, Lr:9.60E-04
Epoch: 6, Train_acc:97.4%, Train_loss:0.086, Test_acc:77.6%, Test_loss:1.591, Lr:9.60E-04
Epoch: 7, Train_acc:96.4%, Train_loss:0.153, Test_acc:76.3%, Test_loss:2.327, Lr:9.41E-04
Epoch: 8, Train_acc:96.4%, Train_loss:0.143, Test_acc:76.3%, Test_loss:1.709, Lr:9.41E-04
Epoch: 9, Train_acc:94.4%, Train_loss:0.237, Test_acc:68.4%, Test_loss:2.247, Lr:9.22E-04
Epoch:10, Train_acc:94.0%, Train_loss:0.262, Test_acc:77.6%, Test_loss:1.967, Lr:9.22E-04
Epoch:11, Train_acc:93.8%, Train_loss:0.191, Test_acc:73.7%, Test_loss:2.434, Lr:9.04E-04
Epoch:12, Train_acc:94.8%, Train_loss:0.190, Test_acc:77.6%, Test_loss:1.816, Lr:9.04E-04
Epoch:13, Train_acc:95.8%, Train_loss:0.145, Test_acc:73.7%, Test_loss:1.538, Lr:8.86E-04
Epoch:14, Train_acc:96.2%, Train_loss:0.109, Test_acc:77.6%, Test_loss:1.935, Lr:8.86E-04
Epoch:15, Train_acc:98.0%, Train_loss:0.101, Test_acc:81.6%, Test_loss:2.159, Lr:8.68E-04
Epoch:16, Train_acc:97.2%, Train_loss:0.108, Test_acc:77.6%, Test_loss:1.773, Lr:8.68E-04
Epoch:17, Train_acc:97.0%, Train_loss:0.063, Test_acc:75.0%, Test_loss:2.138, Lr:8.51E-04
Epoch:18, Train_acc:96.8%, Train_loss:0.130, Test_acc:75.0%, Test_loss:2.099, Lr:8.51E-04
Epoch:19, Train_acc:97.8%, Train_loss:0.091, Test_acc:76.3%, Test_loss:2.193, Lr:8.34E-04
Epoch:20, Train_acc:98.8%, Train_loss:0.033, Test_acc:81.6%, Test_loss:1.693, Lr:8.34E-04
Epoch:21, Train_acc:99.2%, Train_loss:0.017, Test_acc:78.9%, Test_loss:2.050, Lr:8.17E-04
Epoch:22, Train_acc:99.4%, Train_loss:0.021, Test_acc:78.9%, Test_loss:2.249, Lr:8.17E-04
Epoch:23, Train_acc:98.2%, Train_loss:0.036, Test_acc:77.6%, Test_loss:2.074, Lr:8.01E-04
Epoch:24, Train_acc:99.0%, Train_loss:0.024, Test_acc:77.6%, Test_loss:2.390, Lr:8.01E-04
Epoch:25, Train_acc:98.6%, Train_loss:0.072, Test_acc:73.7%, Test_loss:1.968, Lr:7.85E-04
Epoch:26, Train_acc:98.8%, Train_loss:0.029, Test_acc:76.3%, Test_loss:1.795, Lr:7.85E-04
Epoch:27, Train_acc:99.2%, Train_loss:0.021, Test_acc:73.7%, Test_loss:2.494, Lr:7.69E-04
Epoch:28, Train_acc:97.8%, Train_loss:0.062, Test_acc:77.6%, Test_loss:2.291, Lr:7.69E-04
Epoch:29, Train_acc:99.2%, Train_loss:0.030, Test_acc:75.0%, Test_loss:2.210, Lr:7.54E-04
Epoch:30, Train_acc:99.2%, Train_loss:0.022, Test_acc:76.3%, Test_loss:2.601, Lr:7.54E-04
Epoch:31, Train_acc:99.8%, Train_loss:0.011, Test_acc:75.0%, Test_loss:2.691, Lr:7.39E-04
Epoch:32, Train_acc:99.4%, Train_loss:0.014, Test_acc:77.6%, Test_loss:2.066, Lr:7.39E-04
Epoch:33, Train_acc:99.2%, Train_loss:0.014, Test_acc:78.9%, Test_loss:1.779, Lr:7.24E-04
Epoch:34, Train_acc:98.2%, Train_loss:0.056, Test_acc:77.6%, Test_loss:2.174, Lr:7.24E-04
Epoch:35, Train_acc:99.0%, Train_loss:0.036, Test_acc:77.6%, Test_loss:1.847, Lr:7.09E-04
Epoch:36, Train_acc:99.8%, Train_loss:0.006, Test_acc:75.0%, Test_loss:2.411, Lr:7.09E-04
Epoch:37, Train_acc:99.6%, Train_loss:0.014, Test_acc:76.3%, Test_loss:1.594, Lr:6.95E-04
Epoch:38, Train_acc:99.6%, Train_loss:0.019, Test_acc:75.0%, Test_loss:1.905, Lr:6.95E-04
Epoch:39, Train_acc:99.2%, Train_loss:0.017, Test_acc:76.3%, Test_loss:1.660, Lr:6.81E-04
Epoch:40, Train_acc:99.4%, Train_loss:0.023, Test_acc:78.9%, Test_loss:2.124, Lr:6.81E-04
Epoch:41, Train_acc:98.8%, Train_loss:0.065, Test_acc:75.0%, Test_loss:2.457, Lr:6.68E-04
Epoch:42, Train_acc:97.0%, Train_loss:0.075, Test_acc:76.3%, Test_loss:1.730, Lr:6.68E-04
Epoch:43, Train_acc:99.4%, Train_loss:0.046, Test_acc:81.6%, Test_loss:1.590, Lr:6.54E-04
Epoch:44, Train_acc:99.2%, Train_loss:0.035, Test_acc:80.3%, Test_loss:1.773, Lr:6.54E-04
Epoch:45, Train_acc:99.0%, Train_loss:0.026, Test_acc:77.6%, Test_loss:1.742, Lr:6.41E-04
Epoch:46, Train_acc:98.8%, Train_loss:0.051, Test_acc:78.9%, Test_loss:1.645, Lr:6.41E-04
Epoch:47, Train_acc:99.4%, Train_loss:0.028, Test_acc:78.9%, Test_loss:1.641, Lr:6.28E-04
Epoch:48, Train_acc:98.4%, Train_loss:0.039, Test_acc:77.6%, Test_loss:1.982, Lr:6.28E-04
Epoch:49, Train_acc:99.0%, Train_loss:0.036, Test_acc:80.3%, Test_loss:1.473, Lr:6.16E-04
Epoch:50, Train_acc:98.8%, Train_loss:0.058, Test_acc:78.9%, Test_loss:1.719, Lr:6.16E-04
Done
 

四、结果可视化

1、Loss与Accuracy图

In [12]:
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()
 
<Figure size 1200x300 with 2 Axes>
 

2、指定图片进行预测

In [13]:
from PIL import Image 

classes = list(train_dataset.class_to_idx)

def predict_one_image(image_path, model, transform, classes):
    
    test_img = Image.open(image_path).convert('RGB')
    # plt.imshow(test_img)  # 展示预测的图片

    test_img = transform(test_img)
    img = test_img.to(device).unsqueeze(0)
    
    model.eval()
    output = model(img)

    _,pred = torch.max(output,1)
    pred_class = classes[pred]
    print(f'预测结果是:{pred_class}')
In [14]:
# 预测训练集中的某张照片
predict_one_image(image_path='E:/jupyter-notebook/data/5-data/test/adidas/22.jpg', 
                  model=model, 
                  transform=train_transforms, 
                  classes=classes)
 
预测结果是:nike
 

五、保存并加载模型

In [15]:
# 模型保存
PATH = './model.pth'  # 保存的参数文件名
torch.save(model.state_dict(), PATH)

# 将参数加载到model当中
model.load_state_dict(torch.load(PATH, map_location=device))
Out[15]:
<All keys matched successfully>
In [16]:
min_loss = 100000#随便设置一个比较大的数
    for epoch in range(epochs):
        train()
        val_loss = val()
        if val_loss < min_loss:
           min_loss = val_loss
           print("save model")
           torch.save(net.state_dict(),'model.pth')
 
  File "<ipython-input-16-e416a92b2b58>", line 2
    for epoch in range(epochs):
    ^
IndentationError: unexpected indent
posted @   CASTWJ  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示