pytorch 常用线性函数详解

yizhihongxing

PyTorch常用线性函数详解

在本文中,我们将介绍PyTorch中常用的线性函数,包括线性层、批归一化、Dropout和ReLU。我们还将提供两个示例,一个是使用线性层进行图像分类,另一个是使用批归一化进行图像分割。

线性层

线性层是一种将输入张量与权重矩阵相乘并加上偏置向量的操作。在PyTorch中,我们可以使用nn.Linear模块来实现线性层。以下是一个示例:

import torch
import torch.nn as nn

# Define input tensor
x = torch.randn(1, 784)

# Define linear layer
linear = nn.Linear(784, 10)

# Apply linear layer
y = linear(x)

# Print shape of output tensor
print(y.shape)

在这个示例中,我们首先定义了一个输入张量x,它的形状为(1, 784)。接下来,我们定义了一个线性层linear,它将输入张量的大小从(1, 784)转换为(1, 10)。然后,我们将输入张量x应用于线性层,并打印输出张量y的形状。

批归一化

批归一化是一种将输入张量的均值和方差归一化的操作。在PyTorch中,我们可以使用nn.BatchNorm2d模块来实现批归一化。以下是一个示例:

import torch
import torch.nn as nn

# Define input tensor
x = torch.randn(1, 64, 32, 32)

# Define batch normalization layer
batch_norm = nn.BatchNorm2d(64)

# Apply batch normalization
y = batch_norm(x)

# Print shape of output tensor
print(y.shape)

在这个示例中,我们首先定义了一个输入张量x,它的形状为(1, 64, 32, 32)。接下来,我们定义了一个批归一化层batch_norm,它将输入张量的每个通道的均值和方差归一化。然后,我们将输入张量x应用于批归一化层,并打印输出张量y的形状。

Dropout

Dropout是一种在训练过程中随机丢弃一些神经元的操作,以减少过拟合。在PyTorch中,我们可以使用nn.Dropout模块来实现Dropout。以下是一个示例:

import torch
import torch.nn as nn

# Define input tensor
x = torch.randn(1, 64, 32, 32)

# Define dropout layer
dropout = nn.Dropout(p=0.5)

# Apply dropout
y = dropout(x)

# Print shape of output tensor
print(y.shape)

在这个示例中,我们首先定义了一个输入张量x,它的形状为(1, 64, 32, 32)。接下来,我们定义了一个Dropout层dropout,它将输入张量的每个元素随机丢弃一定比例的概率。我们使用p=0.5来指定丢弃50%的概率。然后,我们将输入张量x应用于Dropout层,并打印输出张量y的形状。

ReLU

ReLU是一种常用的激活函数,它将所有负值都设置为零。在PyTorch中,我们可以使用nn.ReLU模块来实现ReLU。以下是一个示例:

import torch
import torch.nn as nn

# Define input tensor
x = torch.randn(1, 64, 32, 32)

# Define ReLU layer
relu = nn.ReLU(inplace=True)

# Apply ReLU
y = relu(x)

# Print shape of output tensor
print(y.shape)

在这个示例中,我们首先定义了一个输入张量x,它的形状为(1, 64, 32, 32)。接下来,我们定义了一个ReLU层relu,它将输入张量的所有负值都设置为零。我们使用inplace=True来指定在原地修改输入张量。然后,我们将输入张量x应用于ReLU层,并打印输出张量y的形状。

示例1:使用线性层进行图像分类

以下是使用线性层进行图像分类的示例代码:

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets

# Define transformation
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])

# Load dataset
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)

# Define data loader
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)

# Define model
model = nn.Sequential(
    nn.Linear(3*32*32, 512),
    nn.ReLU(inplace=True),
    nn.Linear(512, 10)
)

# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# Train model
for epoch in range(10):
    for i, (images, labels) in enumerate(train_loader):
        # Flatten images
        images = images.view(-1, 3*32*32)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # Print loss every 100 batches
        if (i+1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, 10, i+1, len(train_loader), loss.item()))

# Test model
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        # Flatten images
        images = images.view(-1, 3*32*32)

        # Forward pass
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)

        # Compute accuracy
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

在这个示例中,我们首先定义了一个变换transform,它将图像转换为张量并进行归一化。然后,我们加载了CIFAR10数据集,并定义了训练和测试数据加载器。接下来,我们定义了一个包含两个线性层和一个ReLU层的模型。我们使用交叉熵损失函数和随机梯度下降优化器来训练模型。最后,我们在测试集上测试模型,并打印准确率。

示例2:使用批归一化进行图像分割

以下是使用批归一化进行图像分割的示例代码:

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets

# Define transformation
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# Load dataset
train_dataset = datasets.Cityscapes(root='./data', split='train', mode='fine', target_type='semantic', transform=transform)
test_dataset = datasets.Cityscapes(root='./data', split='test', mode='fine', target_type='semantic', transform=transform)

# Define data loader
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=16, shuffle=False)

# Define model
model = nn.Sequential(
    nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(64),
    nn.ReLU(inplace=True),
    nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(64),
    nn.ReLU(inplace=True),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(128),
    nn.ReLU(inplace=True),
    nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(128),
    nn.ReLU(inplace=True),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(512),
    nn.ReLU(inplace=True),
    nn.MaxPool2d(kernel_size=2, stride=2),
    nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(256),
    nn.ReLU(inplace=True),
    nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1),
    nn.BatchNorm2d(128),
    nn.ReLU(inplace=True),
    nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(128),
    nn.ReLU(inplace=True),
    nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1),
    nn.BatchNorm2d(64),
    nn.ReLU(inplace=True),
    nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
    nn.BatchNorm2d(64),
    nn.ReLU(inplace=True),
    nn.Conv2d(64, 19, kernel_size=1, stride=1)
)

# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=0.0005)

# Train model
for epoch in range(10):
    for i, (images, labels) in enumerate(train_loader):
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # Print loss every 100 batches
        if (i+1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, 10, i+1, len(train_loader), loss.item()))

# Test model
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        # Forward pass
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)

        # Compute accuracy
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

在这个示例中,我们首先定义了一个变换transform,它将图像转换为张量并进行归一化。然后,我们加载了Cityscapes数据集,并定义了训练和测试数据加载器。接下来,我们定义了一个包含多个卷积层、批归一化层和反卷积层的模型。我们使用交叉熵损失函数和随机梯度下降优化器来训练模型。最后,我们在测试集上测试模型,并打印准确率。

总结

在本文中,我们介绍了PyTorch中常用的线性函数,包括线性层、批归一化、Dropout和ReLU,并提供了两个示例说明。这些技术对于图像分类和图像分割任务非常有用。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:pytorch 常用线性函数详解 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • tesseract cuda pytorch安装 提升Tesseract-OCR输出的质量

    tesseract下载地址:https://digi.bib.uni-mannheim.de/tesseract/   https://blog.csdn.net/u010454030/article/details/80515501   http://www.freeocr.net/   OpenCV OCR and text recognition wi…

    PyTorch 2023年4月8日
    00
  • 取出预训练模型中间层的输出(pytorch)

    1 遍历子模块直接提取 对于简单的模型,可以采用直接遍历子模块的方法,取出相应name模块的输出,不对模型做任何改动。该方法的缺点在于,只能得到其子模块的输出,而对于使用nn.Sequensial()中包含很多层的模型,无法获得其指定层的输出。 示例 resnet18取出layer1的输出 from torchvision.models import res…

    2023年4月5日
    00
  • pytorch tensor的索引与切片

    tensor索引与numpy类似,支持冒号,和数字直接索引 import torch a = torch.Tensor(2, 3, 4) a # 输出: tensor([[[9.2755e-39, 1.0561e-38, 9.7347e-39, 1.1112e-38], [1.0194e-38, 8.4490e-39, 1.0102e-38, 9.0919e…

    PyTorch 2023年4月8日
    00
  • pytorch repeat 和 expand 函数的使用场景,区别

    x = torch.tensor([0, 1, 2, 3]).float().view(4, 1)def test_assign(x): # 赋值操作 x_expand = x.expand(-1, 3) x_repeat = x.repeat(1, 3) x_expand[:, 1] = torch.tensor([0, -1, -2, -3]) x_re…

    PyTorch 2023年4月8日
    00
  • pytorch 网络可视化

    今天使用hiddenlayer测试了下retinanet网络的可视化。首先,安装hiddlayer,直接pip pip install git+https://github.com/waleedka/hiddenlayer.git然后在终端加载模型并显示: import model, torch import hiddenlayer as hl retina…

    PyTorch 2023年4月6日
    00
  • pytorch 6 build_nn_quickly 快速搭建神经网络

    import torch import torch.nn.functional as F # replace following class code with an easy sequential network class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_ou…

    PyTorch 2023年4月8日
    00
  • 基于Pytorch版yolov5的滑块验证码破解思路详解

    以下是基于PyTorch版yolov5的滑块验证码破解思路详解。 简介 滑块验证码是一种常见的人机验证方式,它通过让用户拖动滑块来验证用户的身份。本文将介绍如何使用PyTorch版yolov5来破解滑块验证码。 步骤 步骤1:数据收集 首先,我们需要收集一些滑块验证码数据。我们可以使用Selenium等工具来模拟用户操作,从而收集大量的滑块验证码数据。 步骤…

    PyTorch 2023年5月15日
    00
  • Pytorch之如何dropout避免过拟合

    PyTorch之如何使用dropout避免过拟合 在深度学习中,过拟合是一个常见的问题。为了避免过拟合,我们可以使用dropout技术。本文将提供一个完整的攻略,介绍如何使用PyTorch中的dropout技术来避免过拟合,并提供两个示例,分别是使用dropout进行图像分类和使用dropout进行文本分类。 dropout技术 dropout是一种常用的正…

    PyTorch 2023年5月15日
    00
合作推广
合作推广
分享本页
返回顶部