1.继承自nn.Module的方式
from torch import nn
import torch.nn.functional as F
'''继承自nn.Module'''class LModel(nn.Module):def __init__(self):super().__init__()self.L1 = nn.Linear(10,10)self.L2 = nn.Linear(10,64)self.L3 = nn.Linear(64,10)self.L4 = nn.Linear(10,5)self.L5 = nn.Linear(5,1)'''也可以不定义这个直接使用F低阶API接口'''self.relu = nn.ReLU()self.sig = nn.Sigmoid()def forward(self, input):x = self.L1(input)x = self.relu(x)'''x = F.relu(x)'''x = self.L2(x)x = self.sig(x)'''x = F.sigmod(x)'''x = self.L3(x)x = self.relu(x)'''x = F.relu(x)'''x = self.L4(x)x = self.relu(x)'''x = F.relu(x)'''x = self.L5(x)x = self.sig(x)'''x = F.sigmod(x)'''return x'''使用模型办法'''
x = np.random.randn(10)
print(x)
x = torch.from_numpy(x).type(torch.float32)
print(x)
model = LModel()
print(model)
x = model(x)
print(x)
2.直接使用 nn.Sequential
model = nn.Sequential(nn.Linear(10,64),nn.ReLU(),nn.Linear(64,25),nn.Tanh(),nn.Linear(25,10),nn.ELU(),nn.Linear(10,5),nn.Sigmoid(),nn.Softmax(dim=0))x = np.random.randn(10)print(x)x = torch.from_numpy(x).type(torch.float32)print(x)x = model(x)print(x)print(x.sum())
定义模型需要用到的函数,基本都在nn这个模块里面有定义。