Pytorch极简入门教程(十三)——批标准化BN层

批标准化BN层

导入必要的模块
import torch
import torch.nn as nn   # 神经网络主要工具箱
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
from torchvision import transforms
# torchvision 有4个功能模块: model、datasets、transforms、utils
"""
model: 针对一些常用的模型
datasets:用来下载一些经典的数据集
transforms: 提供了对PlL Image对象和Tensor对象的常用操作
utils: 
"""

import torchvision      # 神经网络中一些重要的模块
import os
导入数据
base_dir = r"./dataset/4weather"
train_dir = os.path.join(base_dir, "train")
test_dir  = os.path.join(base_dir, "test")
配置训练集和测试集
transform = transforms.Compose([
    transforms.Resize(96, 96),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5],
                         std = [0.5, 0.5, 0.5])
])

train_ds = torchvision.datasets.ImageFolder(
    train_dir,
    transform = transform
)
test_ds = torchvision.datasets.ImageFolder(
    test_dir,
    transform = transform
)

BATCHSIZE = 16

train_dl = torch.utils.data.DataLoader(
    train_ds,
    batch_size = BATCHSIZE,
    shuffle =  True
)

test_dl = torch.utils.data.DataLoader(
    test_dir,
    batch_size = BATCHSIZE
)
创建网络层
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, 3)
        self.bn1 = nn.BatchNorm2d(16)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(16, 32, 2)
        self.bn2 = nn.BatchNorm2d(32)
        self.conv3 = nn.Conv2d(32, 64, 2)
        self.bn3 = nn.BatchNorm2d(64)
        self.drop = nn.Dropout(0.5)
        self.fc1 = nn.Linear(64*10*10, 1024)
        self.bn_fc1 = nn.BatchNorm2d(1024)
        self.fc2 = nn.Linear(1024, 256)
        self.bn_fc2 = nn.BatchNorm2d(256)
        self.fc3 = nn.Linear(256, 4)
    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.bn1(x)
        x = self.pool(F.relu(self.conv2(x)))
        x = self.bn2(x)
        x = self.pool(F.relu(self.conv3(x)))
        x = x.view(-1, 64*10*10)
        x = F.relu(self.fc1(x))
        x = self.bn_fc1(x)
        x = self.drop(x)
        x = F.relu(self.fc2(x))
        x = self.bn_f2(x)
        x = self.drop(x)
        x = self.fc3(x)
        return x
定义优化器和损失函数
model = Net()
if torch.cuda.is_available():
    model.to("cuda:0")

# 优化器
optim = torch.optim.Adam(model.parameters(), lr = 0.001)
loss_fn = nn.CrossEntropyLoss()
定义评判标准
def fit(epoch, model, trainloader, testloader):
    correct = 0
    total = 0
    running_loss = 0
    model.train()
    for x, y in trainloader:
        if torch.cuda.is_available():
            x, y = x.to("cuda:0"),  y.to("cuda:0")
        y_pred = model(x)
        loss = loss_fn(y_pred, y)
        optim.zero_grad()
        loss.backward()
        optim.step()
        with torch.no_grad():
            y_pred = torch.argmax(y_pred, dim=1)
            correct += (y_pred == y).sum().item()
            total += y.size(0)
            running_loss += loss.item()
    epoch_loss = running_loss / len(trainloader.dataset)
    epoch_acc = correct / total

    test_correct = 0
    test_total = 0
    test_running_loss = 0
    model.eval()
    with torch.no_grad():
        for x, y in testloader:
            if torch.cuda.is_available():
                x , y = x.to("cuda:0"), y.to("cuda:0")
            y_pred = model(x)
            test_correct += (y_pred == y).sum().item()
            test_total += y.size(0)
            test_running_loss += loss.item()

    epoch_test_loss = test_running_loss / len(testloader.dataset)
    epoch_test_acc = test_correct / test_total

    print("epoch:", epoch,
          "loss:",  round(epoch_loss, 3),
          "accuracy:",  round(epoch_acc),
          "test_loss:", round(epoch_test_loss, 3),
          "test_accuracy:", round(epoch_test_acc, 3)
        )

    return epoch_loss, epoch_acc, epoch_test_loss, epoch_test_acc
开启训练和测试
epochs = 30
train_loss = []
train_acc = []
test_loss = []
test_acc = []

for epoch in range(epochs):
    epoch_loss, epoch_acc, epoch_test_loss, epoch_test_acc = fit(epoch,
                                                                 model,
                                                                 train_dl,
                                                                 test_dl)
    train_loss.append(epoch_loss)
    train_acc.append(epoch_acc)
    test_loss.append(epoch_test_loss)
    test_acc.append(epoch_test_acc)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch是一个广泛应用于深度学习的开源机器学习库,它提供了丰富的工具和接口,使得开发者可以更加便捷地构建和训练深度神经网络模型。 PyTorch入门教程可以通过以下几个步骤进行: 1. 安装PyTorch:首先需要在计算机中安装PyTorch库。可以通过官方网站或者使用包管理工具(如pip或conda)进行安装。安装完成后,可以在Python环境中导入PyTorch库。 2. 张量操作:PyTorch的核心是张量(Tensor),它是一个多维数组。学习如何创建、操作和使用张量是入门的关键。可以学习如何创建随机张量、更改张量形状、进行基本数学运算等。 3. 构建模型:在PyTorch中构建模型通常使用nn.Module类。可以学习如何定义自己的模型类,包括初始化函数、前向传播函数等。还可以学习如何添加层和激活函数,并了解常用的网络结构,如全连接层、卷积层等。 4. 训练模型:在PyTorch中训练模型通常需要定义损失函数和优化器。可以学习如何选择合适的损失函数,如交叉熵损失函数,以及常用的优化器,如随机梯度下降优化器。还可以学习如何使用训练数据批次来进行前向传播和反向传播,并进行参数更新。 5. 测试和评估:在训练完成后,需要对模型进行测试和评估。可以学习如何使用测试数据进行模型预测,并计算预测结果的准确率、精确率、召回率等指标。 虽然PyTorch入门教程只有300字,但这些步骤可以帮助初学者了解PyTorch的基本概念和操作。通过实践和深入学习,可以逐渐掌握更多高级功能和技巧,从而更好地应用PyTorch进行深度学习研究和应用开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值