zoukankan      html  css  js  c++  java
  • 搭建pytorch神经网络的常用两种方式

    '''本节说明搭建pytorch神经网络的常用两种方式 相比快速搭建法 第一种可以个性化设置网络结构'''
    import torch
    import torch.nn.functional as F 
    #方式1 用 class 继承了一个 torch 中的神经网络结构, 然后对其进行了修改
    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)
    #方式2 快速搭建模型
    net2 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )
    #我们再对比一下两者的结构:
    print(net1)
    '''Net(
      (hidden): Linear(in_features=1, out_features=10, bias=True)
      (predict): Linear(in_features=10, out_features=1, bias=True)
    )'''
    print(net2)
    '''Sequential(
      (0): Linear(in_features=1, out_features=10, bias=True)
      (1): ReLU()
      (2): Linear(in_features=10, out_features=1, bias=True)
    )'''
    '''结论:我们会发现 net2 多显示了一些内容, 这是为什么呢? 
    原来他把激励函数也一同纳入进去了, 但是 net1 中, 
    激励函数实际上是在 forward() 功能中才被调用的. 
    这也就说明了, 相比 net2, net1 的好处就是, 
    你可以根据你的个人需要更加个性化你自己的前向传播过程, 比如(RNN).'''
    
  • 相关阅读:
    hdu4726
    hdu2709
    hdu4706
    hdu4715
    快速幂取模
    快速幂
    asp.net中页面传值
    微信小程序支付
    sql 查询重复记录值取一条
    bower使用
  • 原文地址:https://www.cnblogs.com/xuechengmeigui/p/12388400.html
Copyright © 2011-2022 走看看