前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >pytorch快速搭建神经网络_Sequential操作

pytorch快速搭建神经网络_Sequential操作

作者头像
砸漏
发布2020-10-21 10:37:43
8720
发布2020-10-21 10:37:43
举报
文章被收录于专栏:恩蓝脚本

之前用Class类来搭建神经网络

代码语言:javascript
复制
class Neuro_net(torch.nn.Module):
  """神经网络"""
  def __init__(self, n_feature, n_hidden_layer, n_output):
    super(Neuro_net, self).__init__()
    self.hidden_layer = torch.nn.Linear(n_feature, n_hidden_layer)
    self.output_layer = torch.nn.Linear(n_hidden_layer, n_output)

  def forward(self, input):
    hidden_out = torch.relu(self.hidden_layer(input))
    out = self.output_layer(hidden_out)
    return out
  
net = Neuro_net(2, 10, 2)
print(net)

class类图结构:

使用torch.nn.Sequential() 快速搭建神经网络

代码语言:javascript
复制
net = torch.nn.Sequential(
  torch.nn.Linear(2, 10),
  torch.nn.ReLU(),
  torch.nn.Linear(10, 2)
)
print(net)

Sequential图结构

总结:

我们可以发现,使用torch.nn.Sequential会自动加入激励函数, 但是 class类net 中, 激励函数实际上是在 forward() 功能中才被调用的

使用class类中的torch.nn.Module,我们可以根据自己的需求改变传播过程

如果你需要快速构建或者不需要过多的过程,直接使用torch.nn.Sequential吧

补充知识:【PyTorch神经网络】使用Moudle和Sequential搭建神经网络

Module:

init中定义每个神经层的神经元个数,和神经元层数;

forward是继承nn.Moudle中函数,来实现前向反馈(加上激励函数)

代码语言:javascript
复制
# -*- coding: utf-8 -*-
# @Time  : 2019/11/5 10:43
# @Author : Chen
# @File  : neural_network_impl.py
# @Software: PyCharm
 
import torch
import torch.nn.functional as F
 
#data
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.2 * torch.rand(x.size())
 
 
#第一种搭建方法:Module
# 其中,init中定义每个神经层的神经元个数,和神经元层数;
# forward是继承nn.Moudle中函数,来实现前向反馈(加上激励函数)
class Net(torch.nn.Module):
  def __init__(self):
    #继承__init__函数
    super(Net, self).__init__()
    #定义每层的形式
    #隐藏层线性输出feature- hidden
    self.hidden = torch.nn.Linear(1, 10)
    #输出层线性输出hidden- output
    self.predict = torch.nn.Linear(10, 1)
 
  #实现所有层的连接关系。正向传播输入值,神经网络分析输出值
  def forward(self, x):
    #x首先在隐藏层经过激励函数的计算
    x = F.relu(self.hidden(x))
    #到输出层给出预测值
    x = self.predict(x)
    return x
 
net = Net()
print(net)
 
print('\n\n')
 
#快速搭建:Sequential
#模板:net2 = torch.nn.Sequential()
 
net2 = torch.nn.Sequential(
  torch.nn.Linear(1, 10),
  torch.nn.ReLU(),
  torch.nn.Linear(10, 1)
)
print(net2)

以上这篇pytorch快速搭建神经网络_Sequential操作就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档