25:nn.module

1:nn.Module的介绍

 2.nn.module的好处

(2.1)embed current layers现成的神经网络计算的模块

 (2.2)提供了Sequential容器

 [注]在forward时,不需要多个forward只需要使用self.net(x)即可实现整个网络的forward。

 (2.3)para的管理

 【注】net.parameters()可以获得不含参数名字的值,net.named_parameters()可以获得含参数名字的值。故在使用优化器时,可以直接使用net.parameters()将所有的参数传入即可。

(2.4)modules

[注]上图中sequential()为 direct children。BasicNet(),ReLU(),Linear()均为sequential的children。而sequential(),BasicNet(),ReLU(),Linear()称为module。

 (2.5) to(device)

 (2.6)save and load

 【注】net.state_dict()用于记录所有参数的状态,torch.save()将记录保存到文件中去。load_state_dict()用保存的参数状态初始化。避免了程序停止需要重新train。

(2.7)train/test的切换

 [注]net.eval()可以进行test和train的切换。net为根节点。

(2.8):implement own layer实现自己的网络层

 【注】pytorch中未提供flatten类,可以通过自己定义一个继承自nn.module的类flatten类。因此自己定义的类也可以写入到Sequential()容器中。

【注】nn.sequential中只能写类,不能写入函数(例如:F.ReLU()).

(2.9)own linear layer 定义自己的线性层

 【注】通过nn.Parameter()类对参数进行封装,自动设置了参数regred=true。并且使用Parameter()类进行参数的封装,便于对参数的返回。后期可以使用nn.parameters()方法将参数加载到SGD优化器中。

[注]如果不使用Parameter()类进行封装,自行完成regred=true的操作,后期将无法使用nn.parameters()方法进行返回。

原文地址:https://www.cnblogs.com/jiafeng1996/p/15104835.html