20240207周三
看代码的时候发现 y_pred = self.model(x_dict) 就能调用模型的运行了。
#深入探究# PyTorch中的 forward() 方法详解-CSDN博客
为什么呢?执行上面语句相当于调用forward(x)方法。定义类的是时候写了__call()___方法,call()中写了调用forward的过程,这样实现 “类+参数=实例.方法+参数” 的调用。
其次定义模型结构的时候,def forward(x)并不是只传一个x参数,这里x可以包括这种这样的数据。
torch.nn — PyTorch 2.2 documentation
CONTAINERS 给神经网络定义了一些骨架。将常用的层添加到骨架里。
CLASStorch.nn.
Module
- Base class for all neural network modules.
- Your models should also subclass this class.
- Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes:
import torch.nn as nn
import torch.nn.functional as F
# 自定义的Model继承了nn.Module
#
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
# 输入是x
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
创建一个简单的神经网络
# -*- coding: utf-8 -*-
import torch
from torch import nn
class Tudui(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
output = input + 1
return output
tudui = Tudui()
x = torch.tensor(1.0)
output = tudui(x)
print(output) # tensor(2.)
打断点