目的:
用更简单的方式去搭建同样的回归神经网络。【2.1 Regression 回归】
快速搭建:
1、回顾一下【2.1】的搭建方法,用 class 继承了一个 torch 中的神经网络结构,并对其进行了修改。
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x)) # relu为一个功能
x = self.predict(x)
return x
net1 = Net(1, 10, 1)
2、使用Sequential,在里面一层一层垒神经层即可。
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10), # 线性层
torch.nn.ReLU(), # ReLU函数,这个为一个class,所以在输出时候可以被显示出来
torch.nn.Linear(10, 1) # 线性层
)
3、对比输出:
import torch
import torch.nn.functional as F
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
net1 = Net(1, 10, 1)
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10), # 线性层
torch.nn.ReLU(), # ReLU函数,这个为一个class,所以在输出时候可以被显示出来
torch.nn.Linear(10, 1) # 线性层
)
print(net1)
print(net2)
4、输出结果:
Net(
(hidden): Linear(in_features=1, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=1, bias=True)
)
Sequential(
(0): Linear(in_features=1, out_features=10, bias=True)
(1): ReLU()
(2): Linear(in_features=10, out_features=1, bias=True)
)
Process finished with exit code 0
从输出可以看出,搭建同样的网络,使用Sequential方法更简单。