[torch]如何读取 nn 模型中的权重
[torch]how to read weights in nn model
我使用 itorch notebook 构建了 nn 模型。
model = nn.Sequential()
model:add(nn.Reshape(ninputs))
model:add(nn.Linear(ninputs,noutputs))
向模型输入数据
output = model:forward(input)
然后,我打印模型并得到了这个。
print(model)
nn.Sequential {
[input -> (1) -> (2) -> output]
(1): nn.Reshape(3072)
(2): nn.Linear(3072 -> 10)
}
{
gradInput : DoubleTensor - empty
modules :
{
1 :
nn.Reshape(3072)
{
_input : DoubleTensor - empty
nelement : 3072
train : true
output : DoubleTensor - size: 3072
gradInput : DoubleTensor - empty
size : LongStorage - size: 1
_gradOutput : DoubleTensor - empty
batchsize : LongStorage - size: 2
}
2 :
nn.Linear(3072 -> 10)
{
gradBias : DoubleTensor - size: 10
weight : DoubleTensor - size: 10x3072
train : true
bias : DoubleTensor - size: 10
gradInput : DoubleTensor - empty
gradWeight : DoubleTensor - size: 10x3072
output : DoubleTensor - size: 10
}
}
train : true
output : DoubleTensor - size: 10
}
如何读取nn.linear中的权重?
提前致谢。
哦,类似php
model.modules[2].weight
我发现model.modules[1].weight
和model:get(1).weight
类似,但是都不能像residual block一样从table层获取参数。这样就把residual block作为一个layer。
然而,即使在table层中,我们也可以使用params, gradParams = model:parameters()
来获取每一层的参数。
值得注意的是,在第二种方式中,每一层的网络参数被分成两层,分层排列
我使用 itorch notebook 构建了 nn 模型。
model = nn.Sequential()
model:add(nn.Reshape(ninputs))
model:add(nn.Linear(ninputs,noutputs))
向模型输入数据
output = model:forward(input)
然后,我打印模型并得到了这个。
print(model)
nn.Sequential {
[input -> (1) -> (2) -> output]
(1): nn.Reshape(3072)
(2): nn.Linear(3072 -> 10)
}
{
gradInput : DoubleTensor - empty
modules :
{
1 :
nn.Reshape(3072)
{
_input : DoubleTensor - empty
nelement : 3072
train : true
output : DoubleTensor - size: 3072
gradInput : DoubleTensor - empty
size : LongStorage - size: 1
_gradOutput : DoubleTensor - empty
batchsize : LongStorage - size: 2
}
2 :
nn.Linear(3072 -> 10)
{
gradBias : DoubleTensor - size: 10
weight : DoubleTensor - size: 10x3072
train : true
bias : DoubleTensor - size: 10
gradInput : DoubleTensor - empty
gradWeight : DoubleTensor - size: 10x3072
output : DoubleTensor - size: 10
}
}
train : true
output : DoubleTensor - size: 10
}
如何读取nn.linear中的权重?
提前致谢。
哦,类似php
model.modules[2].weight
我发现model.modules[1].weight
和model:get(1).weight
类似,但是都不能像residual block一样从table层获取参数。这样就把residual block作为一个layer。
然而,即使在table层中,我们也可以使用params, gradParams = model:parameters()
来获取每一层的参数。
值得注意的是,在第二种方式中,每一层的网络参数被分成两层,分层排列