pytorch基础(4)-----搭建模型网络的两种方法

方法一:采用torch.nn.Module模块

import torch
import torch.nn.functional as F #法1
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))
out = self.predict(x)
return x
net1 = Net(2,10,2)
print(net1)

打印的结果:

Net(
(hidden): Linear(in_features=2, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=2, bias=True)
)

方法二:类似keras的sequencial搭建网络的方法

net2 = torch.nn.Sequential(
torch.nn.Linear(2,10),
torch.nn.ReLU(),
torch.nn.Linear(10,2),
)
print(net2)

打印结果:

Sequential(
  (0): Linear(in_features=2, out_features=10, bias=True)
  (1): ReLU()
  (2): Linear(in_features=10, out_features=2, bias=True)
)

上一篇:从Java的角度简单修复Cookie越权漏洞


下一篇:吴裕雄--天生自然Django框架开发笔记:Django Admin 管理工具