之前我们都是使用定义class 的方式来构建神经网络,接下来介绍一种使用简便的方式搭建的 神经网络,跟之前的方法效果是一样的。
#method1
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
#输入的是两个特征,输出的类别也是两个
net=Net(2,10,2)
#method 2 这个是快速搭建神经网络的方法
net2=torch.nn.Sequential(
torch.nn.Linear(2,10),
torch.nn.ReLU(),
torch.nn.Linear(10,2)
)