• 2.搭建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).'''
  • 相关阅读:
    理解Cookie和Session的区别及使用
    数据库事务
    Mybatis和hibernate的优缺点比较
    MyBatis、JDBC相关知识
    JVM学习笔记(一,待整理)
    laravel运行url404错误
    电影TS、TC、SCR、R5、BD、HD等版本是什么意思
    mysql索引
    双系统更改启动顺序
    PHP Deprecated: Comments starting with '#' are deprecated in *.ini 警告解决办法
  • 原文地址:https://www.cnblogs.com/xuechengmeigui/p/12388404.html
Copyright © 2020-2023  润新知