"""
以下两种搭建网络的效果是一样的,很显然第二种方法是非常简洁的
"""
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(),
torch.nn.Linear(10, 1)
)
print(net1) # 打印出net1的网络层结构
"""
Net (
(hidden): Linear (1 -> 10)
(predict): Linear (10 -> 1)
)
"""
print(net2) # 打印出net2的网络层结构
"""
Sequential (
(0): Linear (1 -> 10)
(1): ReLU ()
(2): Linear (10 -> 1)
)
"""