python - PyTorch:从另一个模型加载权重而不保存

标签 python pytorch

假设我在 PyTorch 中有两个模型,如何在不保存权重的情况下通过模型 2 的权重加载模型 1 的权重?
像这样:

model1.weights = model2.weights
在 TensorFlow 中,我可以这样做:
variables1 = model1.trainable_variables
variables2 = model2.trainable_variables
for v1, v2 in zip(variables1, variables2):
    v1.assign(v2.numpy())

最佳答案

假设你有两个相同模型的实例(必须是 nn.Module 的子类),那么你可以使用 nn.Module.state_dict() nn.Module.load_state_dict() .您可以找到州词典的简要介绍here .

model1.load_state_dict(model2.state_dict())

关于python - PyTorch:从另一个模型加载权重而不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66517484/

相关文章:

python - Conda 环境丢失

python - 无法为 AWS Lambda 导入 grequests

neural-network - 如何计算 CNN 中的层数?

python - 我如何重新使用经过训练的 fastai 模型?

deep-learning - 如何修复 "RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.FloatTensor but got torch.LongTensor"

python - 如何将 torch 张量转换为 Pandas 数据帧?

python - PyTorch LSTM dropout 与 Keras LSTM dropout

python - 如何使python中的if-elif-else语句更节省空间?

python - 连续打印文本Python

Python Subversion 包装器库