9.1 帮助文档
Pytorch官网:Docs -> Python API : torch.nn -> Containers -> Module
官方文档中的示例
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__() # 调用父类的初始化函数
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
def forward(self, x): # 正向传播
x = F.relu(self.conv1(x)) # "conv1()"卷积;"relu()"非线性
return F.relu(self.conv2(x)) # 第二次卷积、非线性
9.2 尝试编写
import torch
from torch import nn
class Avlon(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
output = input + 1
return output
avlon = Avlon()
x = torch.tensor(1.0)
output = avlon(x)
print(output)
# 第6、7行代码可通过:Code -> Generate -> Override Methods 完成
运行后输出为:tensor(2.)
在第14行进行断点操作,通过"Step Into My Code"可以查看代码运行每一步的详细情况。