import torch
# 创建张量
x = torch.randn(3,4)
y = torch.zeros(3,4)# 张量运算
z = x + y
自动求导(Autograd):
PyTorch的自动求导系统可以自动计算梯度
通过requires_grad=True启用梯度计算
# 启用自动求导
x = torch.randn(3,4, requires_grad=True)# 计算损失
y = x *2
loss = y.sum()# 反向传播
loss.backward()
计算图:
PyTorch使用动态计算图(Define-by-Run)的方式
每次前向传播都会构建一个新的计算图
二、复杂模型的学习使用
神经网络模块(torch.nn):
torch.nn提供了构建神经网络所需的各种组件
主要包括各种层(如线性层、卷积层)、激活函数、损失函数等
import torch.nn as nn
import torch.nn.functional as F
classNet(nn.Module):def__init__(self):super(Net, self).__init__()
self.fc1 = nn.Linear(784,128)
self.fc2 = nn.Linear(128,10)defforward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)return x
卷积神经网络(CNN):
适用于图像处理任务
包含卷积层、池化层等
classCNN(nn.Module):def__init__(self):super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1,32, kernel_size=3)
self.conv2 = nn.Conv2d(32,64, kernel_size=3)
self.fc1 = nn.Linear(12*12*64,128)
self.fc2 = nn.Linear(128,10)defforward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x,2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x,2)
x = x.view(-1,12*12*64)
x = F.relu(self.fc1(x))
x = self.fc2(x)return x