PyTorch-Sequential網絡快速搭建法
硬件:NVIDIA-GTX1080
軟件:Windows7、python3.6.5、pytorch-gpu-0.4.1
一、基礎知識
1、torch.nn.Sequential()方法與class Net方法有相同功效,且Sequential方法更簡單明瞭!
2、以Linear關係分類爲例(https://blog.csdn.net/samylee/article/details/90719918)
二、代碼展示
class Net(torch.nn.Module): # 繼承 torch 的 Module
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__() # 繼承 Module 的 __init__ 功能
# 定義每層用什麼樣的形式
self.hidden = torch.nn.Linear(n_feature, n_hidden) # 隱藏層線性輸出, type(hidden) = torch.nn.modules.linear.Linear(一個類)
self.output = torch.nn.Linear(n_hidden, n_output) # 輸出層線性輸出, type(predict) = torch.nn.modules.linear.Linear(一個類)
def forward(self, x): # 這同時也是 Module 中的 forward 功能
# 正向傳播輸入值, 神經網絡分析出輸出值
x = Func.relu(self.hidden(x)) # 激勵函數(隱藏層的線性值) self.hidden.forward(x), 其中forward被隱藏,因爲使用了繼承,父類中有@內置
x = self.output(x) # 輸出值 self.predict.forward(x), 其中forward被隱藏
return x
#net = Net(n_feature=2, n_hidden=10, n_output=2)
net = torch.nn.Sequential(
torch.nn.Linear(2, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 2)
)
# print(net) # net 的結構
三、參考:
任何問題請加唯一QQ2258205918(名稱samylee)!