PyTorch-Sequential网络快速搭建法

PyTorch-Sequential网络快速搭建法

硬件:NVIDIA-GTX1080

软件:Windows7、python3.6.5、pytorch-gpu-0.4.1

一、基础知识

1、torch.nn.Sequential()方法与class Net方法有相同功效,且Sequential方法更简单明了!

2、以Linear关系分类为例(https://blog.csdn.net/samylee/article/details/90719918

二、代码展示

class Net(torch.nn.Module):  # 继承 torch 的 Module
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()     # 继承 Module 的 __init__ 功能
        # 定义每层用什么样的形式
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # 隐藏层线性输出, type(hidden) = torch.nn.modules.linear.Linear(一个类)
        self.output = torch.nn.Linear(n_hidden, n_output)   # 输出层线性输出, type(predict) = torch.nn.modules.linear.Linear(一个类)
 
    def forward(self, x):   # 这同时也是 Module 中的 forward 功能
        # 正向传播输入值, 神经网络分析出输出值
        x = Func.relu(self.hidden(x))      # 激励函数(隐藏层的线性值) self.hidden.forward(x), 其中forward被隐藏,因为使用了继承,父类中有@内置
        x = self.output(x)             # 输出值 self.predict.forward(x), 其中forward被隐藏
        return x
        
#net = Net(n_feature=2, n_hidden=10, n_output=2)
        
net = torch.nn.Sequential(
    torch.nn.Linear(2, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 2)
)
 
# print(net)  # net 的结构

三、参考:

https://morvanzhou.github.io/

 

任何问题请加唯一QQ2258205918(名称samylee)!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章