我正在嘗試通過 ONNX 將預先保存的 PyTorch 模型轉換為 TensorFlow 模型。目前,以下代碼是將模型匯出為 .onnx 格式。神經網路有 2 個輸入,一個具有 5 個神經元的隱藏層和一個標量輸出。
這是我正在使用的代碼:
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
class Model(nn.Module):
def __init__(self, n_h_layers, n_h_neurons, dim_in, dim_out, in_bound, out_bound):
super(Model,self).__init__()
self.n_h_layers=n_h_layers
self.n_h_neurons=n_h_neurons
self.dim_in=dim_in
self.dim_out=dim_out
self.in_bound=in_bound
self.out_bound=out_bound
layer_input = [nn.Linear(dim_in, n_h_neurons, bias=True)]
layer_output = [nn.ReLU(), nn.Linear(n_h_neurons, dim_out, bias=True), nn.Hardtanh(in_bound, out_bound)]
# hidden layer
module_hidden = [[nn.ReLU(), nn.Linear(n_h_neurons, n_h_neurons, bias=True)] for _ in range(n_h_layers - 1)]
layer_hidden = list(np.array(module_hidden).flatten())
# nn model
layers = layer_input layer_hidden layer_output
self.model = nn.Sequential(*layers)
print(self.model)
trained_nn=torch.load('path')
trained_model=Model(1,5,2,1,-1,1)
trained_model.load_state_dict(trained_nn,strict=False)
dummy_input=Variable(torch.randn(1,2))
torch.onnx.export(trained_model,dummy_input, 'file.onnx', verbose=True)
我有兩個問題:
- 運行此代碼段會在 module.py 中的 _forward_unimplemented 中引發“NonImplementedError”,如下所示:
File ".../anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 201, in _forward_unimplemented
raise NotImplementedError
NotImplementedError
我不知道 python 中的例外處理,我不知道我必須更改什么才能解決錯誤。
- 當我列印trained_nn時,這就是它給我的:
OrderedDict([('0.weight',
tensor([[ 0.2035, -0.7679],
[ 1.6368, -0.4135],
[-0.0908, -0.2335],
[ 1.3731, -0.3135],
[ 0.6361, 0.2521]])),
('0.bias', tensor([-1.6907, 0.7262, 1.4032, 1.2551, 0.8013])),
('2.weight',
tensor([[-0.4603, -0.0719, 0.4082, -1.0235, -0.0538]])),
('2.bias', tensor([-1.1568]))])
然而,列印trained_model.state_dict()給了我一個具有完全不同的權重和偏差集的神經網路,盡管我相信它應該給我與以前完全相同的模型,因為這是我需要保存為 onnx 檔案的模型?
OrderedDict([('model.0.weight',
tensor([[ 0.4817, 0.0928],
[-0.4313, 0.1253],
[ 0.6681, -0.4029],
[ 0.6474, 0.0029],
[-0.4663, 0.5029]])),
('model.0.bias',
tensor([-0.2292, 0.6674, -0.3755, 0.0778, 0.0527])),
('model.2.weight',
tensor([[-0.2097, -0.3029, 0.2792, 0.2596, 0.1362]])),
('model.2.bias', tensor([-0.1835]))])
不知道我犯了什么錯誤。任何幫助表示贊賞。
uj5u.com熱心網友回復:
- 當你創建一個子類時,
nn.Module你需要實作forward方法。在您的情況下,您需要添加:
class Model(nn.Module):
def __init__(self, n_h_layers, n_h_neurons, dim_in, dim_out, in_bound, out_bound):
super(Model, self).__init__()
...
def forward(self, x):
return self.model(x)
- 引數名稱不匹配:
model.0.weight!=0.weight
model.0.bias!=0.bias
缺少前綴模型。
所以當你load_state_dict()用strict=False引數呼叫時不會被使用。
您可以重命名引數以匹配模型:
trained_nn = torch.load('path')
trained_nn = {f'model.{name}': w for name, w in trained_nn.items()}
trained_model.load_state_dict(trained_nn, strict=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517472.html
標籤:例外神经网络火炬onnx
