深度学习参数管理

1.访问参数

我们从已有模型中访问参数。当通过`Sequential`类定义模型时,我们可以通过索引来访问模型的任意层。

· 检查第二个全连接层的参数。

print(net[2].state_dict())

print(net[2].bias)

print(net[2].bias.data)

net[2].weight

print(*[(name, param.shape) for name, param in net[0].named_parameters()])

print(*[(name, param.shape) for name, param in net.named_parameters()])

2.参数初始化

· 内置初始化

def init_normal(m):

if type(m) == nn.Linear:

nn.init.normal_(m.weight, mean=0, std=0.01)

nn.init.zeros_(m.bias)

net.apply(init_normal)

net[0].weight.data[0], net[0].bias.data[0] #输出

· 不同的层采用不同的初始化

def init_xavier(m):

if type(m) == nn.Linear:

nn.init.xavier_uniform_(m.weight)

def init_42(m):

if type(m) == nn.Linear:

nn.init.constant_(m.weight, 42)

net[0].apply(init_xavier)

net[2].apply(init_42)

print(net[0].weight.data[0])

print(net[2].weight.data)

3.共享参数

我们需要给共享层一个名称,以便可以引用它的参数

shared = nn.Linear(8, 8)

net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(),

shared, nn.ReLU(),

shared, nn.ReLU(),

nn.Linear(8, 1))

net(X)

检查参数是否相同

print(net[2].weight.data[0] == net[4].weight.data[0])

net[2].weight.data[0, 0] = 100

确保它们实际上是同一个对象,而不只是有相同的值

print(net[2].weight.data[0] == net[4].weight.data[0])

相关推荐
倔强青铜三10 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271114 小时前
Python之语言特点
python
刘立军14 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机17 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i20 小时前
django中的FBV 和 CBV
python·django
c8i20 小时前
python中的闭包和装饰器
python
惯导马工20 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列