pytorch 建立模型的几种方法

利用pytorch来构建网络模型,常用的有如下三种方式

前向传播网络具有如下结构:

卷积层--》Relu层--》池化层--》全连接层--》Relu层

对各Conv2d和Linear的解释如下

Conv2d的解释如下
"""
Conv2d(in_channels, out_channels, kernel_size, stride=1,
        padding=0, dilation=1, groups=1, bias=True)

in_channels(int) – 输入信号的通道数
out_channels(int) – 卷积产生的通道数
kerner_size(int or tuple) - 卷积核的大小
stride(int or tuple,optional) - 卷积步长,即要将输入扩大的倍数。
padding(int or tuple, optional) - 输入的每一条边补充0的层数,高宽都增加2*padding
"""
Linear函数的解释如下
"""
Linear(in_features, out_features, bias=True)
in_features: size of each input sample,一般输入是[B,in_features]
out_features: size of each output sample,经过Linear输出的tensor是[B,out_features]
"""

1.建立模型方法

from torch.nn import *
class Network(Module):
    def __init__(self):
        super(Network, self).__init__()
        self.conv = Conv2d(3, 16, 3, 1, 1)
        self.dense =Linear(16 * 3, 2)
        self.pool=MaxPool2d(kernel_size=2)
        self.relu=ReLU(inplace=True)#inplace为True,将会改变输入的数据 ,否则不会改变原输入,只会产生新的输出

    #前向传播方法
    def forward(self, x):
        x=self.conv(x)
        x=  self.relu(x)
        x = MaxPool2d(x, 2)
        x = x.view(x.size(0), -1)#设置成为[B,-1]格式
        x=  self.dense(x)
        x = self.relu(x)
        return x
model = Network()
print(model)

模型各参数如下

Network(
  (conv): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (dense): Linear(in_features=48, out_features=2, bias=True)
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (relu): ReLU(inplace)
)

2.建立模型方法,通过torch.nn.Sequential建立模型

import torch
class Network(torch.nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(3, 16, 3, 1, 1),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(2)
        )
        self.dense = torch.nn.Sequential(
            torch.nn.Linear(16 * 3, 2),
            torch.nn.ReLU()
        )

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size(0), -1)
        x = self.dense(x)
        return x
model = Network()
print(model)

模型各参数如下

Network(
  (conv): Sequential(
    (0): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (dense): Sequential(
    (0): Linear(in_features=48, out_features=2, bias=True)
    (1): ReLU()
  )
)

3.建立模型方法,通过torch.nn.Sequential的方法add_module添加操作

import torch
class Network(torch.nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self.network=torch.nn.Sequential()
        self.network.add_module("conv_{}".format(1),torch.nn.Conv2d(3, 16, 3, 1, 1))
        self.network.add_module("relu_{}".format(1),torch.nn.ReLU())
        self.network.add_module("pool_{}".format(1),torch.nn.MaxPool2d(2))
        self.network.add_module("dense_{}".format(1),torch.nn.Linear(16 * 3, 2))
        self.network.add_module("relu_{}".format(2),torch.nn.ReLU())

    def forward(self, x):
        x = self.network(x)
        return x
model = Network()
print(model)

模型各参数如下

Network(
  (network): Sequential(
    (conv_1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (relu_1): ReLU()
    (pool_1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (dense_1): Linear(in_features=48, out_features=2, bias=True)
    (relu_2): ReLU()
  )
)

原文地址:https://www.cnblogs.com/AntonioSu/p/11979524.html

时间: 2024-08-23 23:22:13

pytorch 建立模型的几种方法的相关文章

django 自定义用户user模型的三种方法

来源:http://www.jb51.net/article/57527.htm django version: 1.7.1 最简单的推荐:使用abstractuser扩充fields 复制代码代码如下: profiles/models.py from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils.translation import ugettext_laz

字典转模型的三种方法之四:总结

模型 1 // 2 // YSFoodTypeModule.h 3 // YSUiSplitViewController 4 // 5 // Created by ys on 15/12/12. 6 // Copyright (c) 2015年 ys. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 @interface YSFoodTypeModule : NSObject 12 13 @proper

评估机器学习模型的几种方法(验证集的重要性)

什么是评估机器学习模型     机器学习的目的是得到可以泛化(generalize)的模型,即在前所未见的数据上表现很好的模型,而过拟合则是核心难点.你只能控制可以观察的事情,所以能够可靠地衡量模型的泛化能力非常重要. 如何衡量泛化能力,即如何评估机器学习模型. 评估模型的重点是将数据划分为三个集合:训练集.验证集和测试集.在训练数据上训练模型,在验证数据上评估模型.一旦找到了最佳参数,就在测试数据上最后测试一次. 为什么需要验证集 原因在于开发模型时总是需要调节模型配置,比如选择层数或每层大小

ThinkPHP学习笔记 实例化模型的四种方法

创建Action类 [php] <?php class NewObjectAction extends Action{ public function index(){ //1.创建一个基础模型 //      //一:实例化一个系统的数据库操作类 //      //new Model('User')相当于M('User'),在Model中放置一个需要操作的表 //      //1命名: //      //  thinkphp默认的有表名前缀,如果为think_user:则在Model中可

图的建立和遍历两种方法(转载)

/************************************************************************//* 图的邻接表存储结构                                                    *//************************************************************************/#ifdef _MSC_VER#define _CRTDBG_MAP_A

字典转模型的三种方法之三:MJExtension全自动字典模型互转

1 #import "YSHomeViewController.h" 2 #import "UIImage+YS.h" 3 #import "UIBarButtonItem+YS.h" 4 #import "YStitleButton.h" 5 #import "AFNetworking.h" 6 #import "YSaccountTool.h" 7 #import "YSa

字典转模型的三种方法之二:KVC

1 -(NSArray *)tgs 2 { 3 NSString *path = [[NSBundle mainBundle]pathForResource:@"tgs" ofType:@"plist"]; 4 NSMutableArray *tgsArray = [NSMutableArray array]; 5 NSArray *tgsDicts = [NSArray arrayWithContentsOfFile:path]; 6 for (NSDiction

2种方法筛选出多因子量化选股模型

多因子选股模型在模型搭建中,往往会涉及到非常多的股价影响因子,并可能导出数量极多的备选模型.因此,对于多因子选股模型的评价和筛选,就显得尤为关键. 对于专业的量化投资人而言,就需要进一步了解多因子选股模型的两种主要的评价判断方法——打分法和回归法. 打分法的评价原理和流程 所谓打分法,就是根据各个因子的大小对股票进行打分,然后按照一定的权重加权得到一个总分,最后根据总分再对股票进行筛选. 对于多因子模型的评价而言,实际通过评分法回测出的股票组合收益率,就能够对备选的选股模型做出优劣评价. 打分法

bootstrap, boosting, bagging 几种方法的联系

http://blog.csdn.net/jlei_apple/article/details/8168856 这两天在看关于boosting算法时,看到一篇不错的文章讲bootstrap, jackknife, bagging, boosting, random forest 都有介绍,以下是搜索得到的原文,没找到博客作者的地址, 在这里致谢作者的研究. 一并列出一些找到的介绍boosting算法的资源: (1)视频讲义,介绍boosting算法,主要介绍AdaBoosing    http: