week3:基于pytorch的天气图像识别实验

基于pytorch的天气图像识别实验

Ⅰ Ⅰ Introduction:
  • 本文是基于pytorch完成天气识别分类任务的实验记录。
  • 实验目标:
    • 学习本地读取加载数据
    • 熟练构建并使用CNN网络
    • 测试集acc达标93%+
    • 学习分割数据集
Ⅱ Ⅱ Experiment:
  1. 数据准备与任务分析:
  • 数据集为本地已准备好
  • 通过分割数据为测试与训练,训练模型至在测试集上有优良表现。
  1. 配置环境:
    语言环境:python 3.8
    编译器: pycharm
    深度学习环境:
    torch2.11
    cuda12.1
    torchvision
    0.15.2a0
  2. 构建网络:
  • 导入数据:
data_dir = './data/'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]



import matplotlib.pyplot as plt
from PIL import Image
image_folder = './data/cloudy/'

image_files = [f for f in os.listdir(image_folder) if f.endswith((".jpg", ".png", ".jpeg"))]

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 = Image.open(img_path)
    ax.imshow(img)
    ax.axis('off')

plt.tight_layout()
plt.show()

total_datadir = './data/'

train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  
    transforms.ToTensor(),          
    transforms.Normalize(           
        mean=[0.485, 0.456, 0.406], 
        std=[0.229, 0.224, 0.225])  
])

total_data = datasets.ImageFolder(total_datadir,transform=train_transforms)

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])

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)

在这里插入图片描述

  • 网络结构:
import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
        """
        nn.Conv2d()函数:
        第一个参数(in_channels)是输入的channel数量
        第二个参数(out_channels)是输出的channel数量
        第三个参数(kernel_size)是卷积核大小
        第四个参数(stride)是步长,默认为1
        第五个参数(padding)是填充大小,默认为0
        """
        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.pool1 = nn.MaxPool2d(2,2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn5 = nn.BatchNorm2d(24)
        self.pool2 = nn.MaxPool2d(2,2)
        self.fc1 = nn.Linear(24*50*50, len(classeNames))

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))      
        x = F.relu(self.bn2(self.conv2(x)))     
        x = self.pool1(x)                        
        x = F.relu(self.bn4(self.conv4(x)))     
        x = F.relu(self.bn5(self.conv5(x)))  
        x = self.pool2(x)                        
        x = x.view(-1, 24*50*50)
        x = self.fc1(x)

        return x

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

model = Network_bn().to(device)
model

  • torch.nn.MaxPool2d():
    • kernel_size:最大的窗口大小
    • stride:窗口的步幅,默认值为kernel_size
    • padding:填充值,默认为0
    • dilation:控制窗口中元素步幅的参数
  1. 训练模型:
    训练函数:
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共60000张图片
    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

  1. 测试模型:
    测试函数:
def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,313(10000/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
  1. 实验结果及可视化:
    编写主函数:
if __name__ == '__main__':
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    data_dir = './data/'
    data_dir = pathlib.Path(data_dir)

    data_paths = list(data_dir.glob('*'))
    classeNames = [str(path).split("\\")[1] for path in data_paths]

    image_folder = './data/cloudy/'

    image_files = [f for f in os.listdir(image_folder) if f.endswith((".jpg", ".png", ".jpeg"))]

    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 = Image.open(img_path)
        ax.imshow(img)
        ax.axis('off')

    plt.tight_layout()
    plt.show()

    total_datadir = './data/'

    train_transforms = transforms.Compose([
        transforms.Resize([224, 224]),
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],
            std=[0.229, 0.224, 0.225])
    ])

    total_data = datasets.ImageFolder(total_datadir, transform=train_transforms)

    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])

    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)

    model = Network_bn().to(device)

    loss_fn = nn.CrossEntropyLoss()
    learn_rate = 1e-4  # 学习率
    opt = torch.optim.SGD(model.parameters(), lr=learn_rate)
    epochs = 30
    train_loss = []
    train_acc = []
    test_loss = []
    test_acc = []

    for epoch in range(epochs):

        model.train()
        epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)

        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)
        print("Using {} device".format(device))
        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')

    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()

经过30轮训练,可以看到在训练集上有较好的拟合效果,并且也在测试集达到了93的准确率:

Using cuda device
Epoch: 1, Train_acc:58.0%, Train_loss:1.043, Test_acc:66.7%,Test_loss:0.993
Using cuda device
Epoch: 2, Train_acc:79.3%, Train_loss:0.641, Test_acc:83.6%,Test_loss:0.548
Using cuda device
Epoch: 3, Train_acc:85.6%, Train_loss:0.533, Test_acc:84.9%,Test_loss:0.455
Using cuda device
Epoch: 4, Train_acc:85.3%, Train_loss:0.469, Test_acc:88.4%,Test_loss:0.418
Using cuda device
Epoch: 5, Train_acc:86.4%, Train_loss:0.427, Test_acc:89.8%,Test_loss:0.393
Using cuda device
Epoch: 6, Train_acc:88.0%, Train_loss:0.384, Test_acc:90.7%,Test_loss:0.396
Using cuda device
Epoch: 7, Train_acc:89.6%, Train_loss:0.362, Test_acc:91.1%,Test_loss:0.291
Using cuda device
Epoch: 8, Train_acc:89.8%, Train_loss:0.319, Test_acc:90.2%,Test_loss:0.367
Using cuda device
Epoch: 9, Train_acc:90.9%, Train_loss:0.294, Test_acc:92.4%,Test_loss:0.273
Using cuda device
Epoch:10, Train_acc:90.6%, Train_loss:0.301, Test_acc:91.1%,Test_loss:0.272
Using cuda device
Epoch:11, Train_acc:90.4%, Train_loss:0.301, Test_acc:91.1%,Test_loss:0.263
Using cuda device
Epoch:12, Train_acc:91.4%, Train_loss:0.266, Test_acc:92.0%,Test_loss:0.260
Using cuda device
Epoch:13, Train_acc:92.1%, Train_loss:0.266, Test_acc:90.2%,Test_loss:0.349
Using cuda device
Epoch:14, Train_acc:93.0%, Train_loss:0.259, Test_acc:91.6%,Test_loss:0.273
Using cuda device
Epoch:15, Train_acc:93.7%, Train_loss:0.243, Test_acc:91.1%,Test_loss:0.294
Using cuda device
Epoch:16, Train_acc:93.7%, Train_loss:0.251, Test_acc:90.7%,Test_loss:0.559
Using cuda device
Epoch:17, Train_acc:93.8%, Train_loss:0.215, Test_acc:92.0%,Test_loss:0.219
Using cuda device
Epoch:18, Train_acc:92.4%, Train_loss:0.230, Test_acc:92.4%,Test_loss:0.235
Using cuda device
Epoch:19, Train_acc:94.1%, Train_loss:0.194, Test_acc:92.4%,Test_loss:0.226
Using cuda device
Epoch:20, Train_acc:93.7%, Train_loss:0.198, Test_acc:92.9%,Test_loss:0.209
Using cuda device
Epoch:21, Train_acc:95.8%, Train_loss:0.173, Test_acc:93.3%,Test_loss:0.224
Using cuda device
Epoch:22, Train_acc:94.6%, Train_loss:0.174, Test_acc:92.9%,Test_loss:0.284
Using cuda device
Epoch:23, Train_acc:93.7%, Train_loss:0.205, Test_acc:93.3%,Test_loss:0.203
Using cuda device
Epoch:24, Train_acc:94.3%, Train_loss:0.197, Test_acc:91.1%,Test_loss:0.256
Using cuda device
Epoch:25, Train_acc:96.0%, Train_loss:0.165, Test_acc:92.9%,Test_loss:0.200
Using cuda device
Epoch:26, Train_acc:96.1%, Train_loss:0.162, Test_acc:93.3%,Test_loss:0.205
Using cuda device
Epoch:27, Train_acc:96.2%, Train_loss:0.166, Test_acc:91.1%,Test_loss:0.257
Using cuda device
Epoch:28, Train_acc:96.2%, Train_loss:0.153, Test_acc:92.0%,Test_loss:0.229
Using cuda device
Epoch:29, Train_acc:96.9%, Train_loss:0.140, Test_acc:93.8%,Test_loss:0.197
Using cuda device
Epoch:30, Train_acc:96.1%, Train_loss:0.152, Test_acc:93.3%,Test_loss:0.194
Done

进程已结束,退出代码0

在这里插入图片描述

Ⅲ Ⅲ Conclusion:
  • 通过本次实验学习到了,从本地加载并分割数据集的方法。同时对CNN的搭建和使用有了进一步掌握。
  • 对于过拟合问题有了初步的认识,在实验中尝试了不同参数,对于训练集的过度训练很容易导致过拟合,使得模型在测试集的表现反而下降。解决过拟合的方法有许多,这是未来值得我进一步学习的地方。
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值