神经网络的工具主要在torch.nn中。
Container——主要是对神经网络定义骨架,定义结构。主要有常用的6个模块👇
实例👇
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(0)
print(output)
为什么这里的可以直接传入参数?
chatgpt回答:
在这段代码中,可以将参数x传入tudui(x)的原因是因为在PyTorch中,Tensor对象是可以作为输入参数传递给模型的。在这里,x是一个包含单个浮点数值1.0的Tensor。当调用tudui(x)时,实际上是调用了
Tudui
类中的forward
方法,并将x作为输入传递给该方法。在forward
方法中,输入参数input被加上1,并返回该结果作为输出。因此,在打印output
时,会得到x+1的结果,即2.0。需要注意的是,PyTorch中的Tensor对象在进行数学运算时会自动实现元素级别的操作,所以在这里直接将Tensor对象x与1相加是合法的操作。