传统法搭建神经网络:
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))
y = self.predict(x)
return y
net1 = Net(1, 10, 1)
print(net1)
传统法搭建神经网络:print(net1)结果为:
Net(
(hidden): Linear(in_features=1, out_features=10)
(predict): Linear(in_features=10, out_features=1)
)
快速法搭建神经网络:
import torch
import torch.nn.functional as f
# 快速法搭建神经网络模型
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1),
)
print(net2)
快速法搭建神经网络:print(net2)结果为:
Sequential(
(0): Linear(in_features=1, out_features=10)
(1): ReLU()
(2): Linear(in_features=10, out_features=1)
)
输出结果本质上是一致的