使用 nn::sequential 访问权重和偏差
Access Weight and Bias with nn::sequential
如果我定义 std::vector<torch::nn::Linear> linear_layers;
并用一些 torch::nn::Linear
对象填充此向量,那么我可以通过 linear_layers[k].weight
访问 weight
和 bias
值, linear_layers[k].bias
。其他图层类型也可以使用相同的功能,例如 torch::nn::Conv2d
。
如果使用 nn::sequential
创建我的网络,然后推回 Linear
或 Conv2d
我无法直接访问 weight
和 bias
。现在,我的问题是,当我使用 nn::sequential
时,如何访问每一层的权重和偏差值?
谢谢,
阿夫欣
这是灵魂:[参见 link https://discuss.pytorch.org/t/common-class-of-linear-conv-etc/39987/8 ]
包括
使用命名空间火炬;
使用命名空间 torch::nn;
int main()
{
auto net = Sequential(Conv2d(1 /输入通道/, 1 /输出通道/, 2 /内核大小/),
Conv2d(1, 1, 2));
for (auto& p : net->named_parameters()) {
NoGradGuard no_grad;
// Access name.
std::cout << p.key() << std::endl;
// Access weigth and bias.
p.value().zero_(); // set all zero
std::cout << p.value() << std::endl;
}
return 0;
}
顺序层具有以下命名约定:.,例如查看控制台输出
0.weight # name of the layer
(1,1,.,.) =
0 0
0 0
[ Variable[CPUFloatType]{1,1,2,2} ]
0.bias
0
[ Variable[CPUFloatType]{1} ]
1.weight
(1,1,.,.) =
0 0
0 0
[ Variable[CPUFloatType]{1,1,2,2} ]
1.bias
0
[ Variable[CPUFloatType]{1} ]
如果我定义 std::vector<torch::nn::Linear> linear_layers;
并用一些 torch::nn::Linear
对象填充此向量,那么我可以通过 linear_layers[k].weight
访问 weight
和 bias
值, linear_layers[k].bias
。其他图层类型也可以使用相同的功能,例如 torch::nn::Conv2d
。
如果使用 nn::sequential
创建我的网络,然后推回 Linear
或 Conv2d
我无法直接访问 weight
和 bias
。现在,我的问题是,当我使用 nn::sequential
时,如何访问每一层的权重和偏差值?
谢谢, 阿夫欣
这是灵魂:[参见 link https://discuss.pytorch.org/t/common-class-of-linear-conv-etc/39987/8 ]
包括
使用命名空间火炬; 使用命名空间 torch::nn;
int main() { auto net = Sequential(Conv2d(1 /输入通道/, 1 /输出通道/, 2 /内核大小/), Conv2d(1, 1, 2));
for (auto& p : net->named_parameters()) {
NoGradGuard no_grad;
// Access name.
std::cout << p.key() << std::endl;
// Access weigth and bias.
p.value().zero_(); // set all zero
std::cout << p.value() << std::endl;
}
return 0;
}
顺序层具有以下命名约定:.,例如查看控制台输出
0.weight # name of the layer
(1,1,.,.) =
0 0
0 0
[ Variable[CPUFloatType]{1,1,2,2} ]
0.bias
0
[ Variable[CPUFloatType]{1} ]
1.weight
(1,1,.,.) =
0 0
0 0
[ Variable[CPUFloatType]{1,1,2,2} ]
1.bias
0
[ Variable[CPUFloatType]{1} ]