deep-learning - 重置网络 [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
准确率在提高,这意味着模型在训练一倍后没有重新初始化。有没有更好的方法来做到这一点?
解决方案
我不认为你重置模型参数的方式是最好的。您遍历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.
推荐阅读
- docker - kafka 生产者 docker 无法连接到代理 docker - AWS
- javascript - A-frame:从内部池中获取球体
不可见 - hibernate-search - 如何在 JSON 对象属性上动态创建索引(JSON 对象道具也是动态的)
- javascript - How copy value of input text to other inputs texts
- amazon-web-services - 当我从本地 IdP SAML SSO 登录 AWS 时出现 ExpiredTokenException
- ubuntu - 试图了解如何配置单独的 logrotate 配置
- sql - 如何修剪在每个结果处发生变化的字符串
- c - 控制UC1638图形液晶屏
- c# - 使用 C# 在 Word 中访问拆分的表格单元格
- javascript - 如何使用Javascript将原始图像字节数组转换为PNG图像