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

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类图结构:

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

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

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

Sequential图结构

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

总结:

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

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

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

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

Module:

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

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

# -*- 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操作

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

标签:
pytorch,神经网络,Sequential

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

评论“pytorch快速搭建神经网络_Sequential操作”

暂无“pytorch快速搭建神经网络_Sequential操作”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。