PyTorch torch功能

2025-06-25 13:50 更新

一、PyTorch 简介

PyTorch 是一款开源的机器学习框架,它具有动态计算图、强大的 GPU 支持和易于使用的 API 等优势,广泛应用于深度学习领域。

二、torch.nn.functional 模块基础

torch.nn.functional 是 PyTorch 中用于实现各种神经网络操作的函数集合。它提供了丰富的函数用于构建和训练神经网络,包括卷积、池化、激活函数、损失函数等。

1. 卷积函数

卷积操作是卷积神经网络(CNN)的核心组件,用于提取数据的空间特征。

一维卷积

import torch
import torch.nn.functional as F


## 创建输入张量 (batch_size, channels, length)
inputs = torch.randn(20, 16, 50)


## 创建卷积核 (out_channels, in_channels, kernel_size)
filters = torch.randn(33, 16, 3)


## 应用一维卷积
output = F.conv1d(inputs, filters)


print("输入张量形状:", inputs.shape)
print("输出张量形状:", output.shape)

运行结果示例:

输入张量形状: torch.Size([20, 16, 50])
输出张量形状: torch.Size([20, 33, 48])

二维卷积

## 创建输入张量 (batch_size, channels, height, width)
inputs = torch.randn(1, 4, 5, 5)


## 创建卷积核 (out_channels, in_channels, kernel_height, kernel_width)
filters = torch.randn(8, 4, 3, 3)


## 应用二维卷积,添加 padding
output = F.conv2d(inputs, filters, padding=1)


print("输入张量形状:", inputs.shape)
print("输出张量形状:", output.shape)

运行结果示例:

输入张量形状: torch.Size([1, 4, 5, 5])
输出张量形状: torch.Size([1, 8, 5, 5])

三维卷积

## 创建输入张量 (batch_size, channels, depth, height, width)
inputs = torch.randn(20, 16, 50, 10, 20)


## 创建卷积核 (out_channels, in_channels, kernel_depth, kernel_height, kernel_width)
filters = torch.randn(33, 16, 3, 3, 3)


## 应用三维卷积
output = F.conv3d(inputs, filters)


print("输入张量形状:", inputs.shape)
print("输出张量形状:", output.shape)

运行结果示例:

输入张量形状: torch.Size([20, 16, 50, 10, 20])
输出张量形状: torch.Size([20, 33, 48, 8, 18])

2. 池化函数

池化操作用于对数据进行下采样,减少数据量,同时保留重要特征。

平均池化

## 创建输入张量 (batch_size, channels, length)
inputs = torch.randn(1, 4, 50)


## 应用一维平均池化
output = F.avg_pool1d(inputs, kernel_size=3, stride=2)


print("输入张量形状:", inputs.shape)
print("输出张量形状:", output.shape)

运行结果示例:

输入张量形状: torch.Size([1, 4, 50])
输出张量形状: torch.Size([1, 4, 24])

最大池化

## 创建输入张量 (batch_size, channels, length)
inputs = torch.randn(1, 4, 50)


## 应用一维最大池化
output = F.max_pool1d(inputs, kernel_size=3, stride=2)


print("输入张量形状:", inputs.shape)
print("输出张量形状:", output.shape)

运行结果示例:

输入张量形状: torch.Size([1, 4, 50])
输出张量形状: torch.Size([1, 4, 24])

3. 激活函数

激活函数为神经网络引入非线性,使网络能够学习复杂的模式。

ReLU 激活函数

## 创建输入张量
inputs = torch.randn(2, 3)


## 应用 ReLU 激活函数
output = F.relu(inputs)


print("输入张量:\n", inputs)
print("输出张量:\n", output)

运行结果示例:

输入张量:
 tensor([[ 0.1234, -0.5678,  0.9012],
         [-1.2345,  0.6789, -0.3456]])
输出张量:
 tensor([[ 0.1234,  0.0000,  0.9012],
         [ 0.0000,  0.6789,  0.0000]])

Sigmoid 激活函数

## 创建输入张量
inputs = torch.randn(2, 3)


## 应用 Sigmoid 激活函数
output = F.sigmoid(inputs)


print("输入张量:\n", inputs)
print("输出张量:\n", output)

运行结果示例:

输入张量:
 tensor([[ 0.1234, -0.5678,  0.9012],
         [-1.2345,  0.6789, -0.3456]])
输出张量:
 tensor([[0.5312, 0.3622, 0.7109],
         [0.2242, 0.6642, 0.4156]])

4. 损失函数

损失函数用于衡量模型预测结果与真实值之间的差异。

均方误差损失

## 创建预测值和真实值张量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.randn(3, 5)


## 应用均方误差损失
loss = F.mse_loss(predictions, targets)


print("损失值:", loss.item())

运行结果示例:

损失值: 0.8765

交叉熵损失

## 创建预测值和真实值张量
predictions = torch.randn(3, 5, requires_grad=True)
targets = torch.empty(3, dtype=torch.long).random_(5)


## 应用交叉熵损失
loss = F.cross_entropy(predictions, targets)


print("损失值:", loss.item())

运行结果示例:

损失值: 1.2345

三、代码实操环节

实操 1:构建简单的神经网络

import torch
import torch.nn as nn
import torch.nn.functional as F


## 定义一个简单的神经网络
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(5, 10)  # 输入层到隐藏层
        self.fc2 = nn.Linear(10, 3)  # 隐藏层到输出层


    def forward(self, x):
        x = F.relu(self.fc1(x))  # 应用 ReLU 激活函数
        x = self.fc2(x)
        return x


## 创建网络实例
net = SimpleNet()


## 创建输入数据
input_data = torch.randn(2, 5)


## 前向传播
output = net(input_data)


print("输入数据形状:", input_data.shape)
print("输出数据形状:", output.shape)

运行结果示例:

输入数据形状: torch.Size([2, 5])
输出数据形状: torch.Size([2, 3])

实操 2:训练神经网络

## 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)


## 训练数据
train_data = torch.randn(100, 5)
train_labels = torch.randn(100, 3)


## 训练循环
for epoch in range(100):
    # 前向传播
    outputs = net(train_data)
    loss = criterion(outputs, train_labels)


    # 反向传播和优化
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


    if (epoch+1) % 10 == 0:
        print(f'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}')

运行结果示例:

Epoch [10/100], Loss: 0.8765
Epoch [20/100], Loss: 0.7654
...
Epoch [100/100], Loss: 0.1234

四、总结与展望

本教程从零基础出发,带领大家认识了 PyTorch 环境,了解了 torch.nn.functional 模块中的基本概念,包括卷积函数、池化函数、激活函数和损失函数等内容,并通过代码实操环节加深了对所学知识的理解。后续可以继续探索更多 PyTorch 相关知识,如自动梯度、神经网络的构建与训练等。

希望这篇教程能够帮助大家更好地入门 PyTorch,如果在学习过程中有任何疑问,欢迎访问编程狮(W3Cschool)官网获取更多资源和支持。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号