用pytorch加載訓練好的模型的時候遇到了如下的問題:
AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'
到網上查了一下是由于訓練模型時使用的是新版本的pytorch,而加載時使用的是舊版本的pytorch。
解決方法:
1、既然是pytorch版本較老,那最簡單的解決方法當然是簡單的更新一下pytorch就ok了。
2、國外的大神給了另一種解決方法,就是在程式開頭添加下面的代碼,即可以使老版本pytorch相容新版本pytorch,參考連結https://discuss.pytorch.org/t/question-about-rebuild-tensor-v2/14560
import torch._utils
try:
torch._utils._rebuild_tensor_v2
except AttributeError:
def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
tensor.requires_grad = requires_grad
tensor._backward_hooks = backward_hooks
return tensor
torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2