首页 > 解决方案 > 重置网络 [pytorch] 的模型参数和权重以进行交叉验证

问题描述

我想在我的训练中实施 5 折交叉验证。每次折叠,我都需要重置模型的参数。在训练某个折叠之前,我添加了以下代码:

for i, (train_index, val_index) in enumerate(kf.split(trainset)):
   for layer in model.children():
       if hasattr(layer, 'reset_parameters'):
           layer.reset_parameters()

每个折叠运行 5 个 epoch。观察结果,我们有:

Fold 1
Best valid accuracy: 0.806000
Fold 2
Best valid accuracy: 0.852000
Fold 3
Best valid accuracy: 0.930900

准确率在提高,这意味着模型在训练一倍后没有重新初始化。有没有更好的方法来做到这一点?

标签: deep-learningneural-networkpytorchconv-neural-network

解决方案


我不认为你重置模型参数的方式是最好的。您遍历model.children()层,但可能这些层有自己的孩子等等。

我认为重置模型参数的最佳方法是使用 init 函数;像这样的东西:

def init_weights(m):
    if isinstance(m, nn.Embedding):
        nn.init.normal_(m.weight, mean=0.0, std=0.1) ## or simply use your layer.reset_parameters()
    if isinstance(m, nn.Linear):
        nn.init.normal_(m.weight, mean=0.0, std=np.sqrt(1 / m.in_features))
        if m.bias is not None: 
            nn.init.zeros_(m.bias)
    if isinstance(m, nn.Conv1d):
        nn.init.normal_(m.weight, mean=0.0, std=np.sqrt(4 / m.in_channels))
        if m.bias is not None: 
            nn.init.zeros_(m.bias)

然后将该函数应用于模型:

model.apply(init_weights)
```

By this way, you scan all layers in your model.

推荐阅读