注意
在本教學課程的上一個階段中,我們使用 PyTorch 來建立機器學習模型。 不過,該模型是一個 .pth 檔案。 若要能夠將其與 Windows ML 應用程式整合,您必須將模型轉換成 ONNX 格式。
Tip
本文為 PyTorch 影像分類教學。 關於 PyTorch 資料分析流程,請參見 「將您的 PyTorch 模型轉換為 ONNX 格式」。
匯出模型
若要匯出模型,請使用 torch.onnx.export() 函式。 此函式會執行模型,並記錄用來計算輸出的運算符追蹤。
- 將下列程式碼複製到 Visual Studio 中的
PyTorchTraining.py檔案,在您的 main 函式上方。
import torch.onnx
#Function to Convert to ONNX
def Convert_ONNX():
# set the model to inference mode
model.eval()
# Let's create a dummy input tensor
dummy_input = torch.randn(1, input_size, requires_grad=True)
# Export the model
torch.onnx.export(model, # model being run
dummy_input, # model input (or a tuple for multiple inputs)
"ImageClassifier.onnx", # where to save the model
export_params=True, # store the trained parameter weights inside the model file
opset_version=10, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['modelInput'], # the model's input names
output_names = ['modelOutput'], # the model's output names
dynamic_axes={'modelInput' : {0 : 'batch_size'}, # variable length axes
'modelOutput' : {0 : 'batch_size'}})
print(" ")
print('Model has been converted to ONNX')
請務必在導出模型之前呼叫 model.eval() 或 model.train(False) ,因為這會將模型設定為 推斷模式。 這是必要的,因為像 dropout 或 batchnorm 這樣的運算符在推斷和訓練模式下的行為不同。
- 若要執行對 ONNX 的轉換,請將對轉換函式的呼叫新增至 main 函式。 您不需要再次定型模型,因此我們會將不再需要執行的一些函式註解掉。 您的主要函式如下所示。
if __name__ == "__main__":
# Let's build our model
#train(5)
#print('Finished Training')
# Test which classes performed well
#testAccuracy()
# Let's load the model we just created and test the accuracy per label
model = Network()
path = "myFirstModel.pth"
model.load_state_dict(torch.load(path))
# Test with batch of images
#testBatch()
# Test how the classes performed
#testClassess()
# Conversion to ONNX
Convert_ONNX()
- 選取工具列上的
Start Debugging按鈕或按下F5,再次執行專案。 不需要再次訓練模型,只要從專案資料夾載入現有的模型即可。
輸出如下所示。
流覽至您的專案位置,並在 .pth 模型旁邊尋找 ONNX 模型。
注意
有興趣深入了解嗎? 檢閱 PyTorch 匯出模型教學課程。
檢視您的模型。
使用 Netron 開啟
ImageClassifier.onnx模型檔案。選取數據節點以開啟模型屬性。
如您所見,模型需要 32 位元張量(多維陣列)float 物件做為輸入,並傳回 Tensor float 物件做為輸出。 輸出陣列會包含每個標籤的機率。 您建置模型的方式,標籤會以10個數字表示,而每個數字都代表物件的十個類別。
| 標籤 0 | 標籤 1 | 標籤 2 | 標籤 3 | 標籤 4 | 標籤 5 | 標籤 6 | 標籤 7 | 標籤 8 | 標籤 9 |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 平面 | 汽車 | 鳥 | 貓 | 鹿 | 狗 | 青蛙 | 馬 | 發佈 | 卡車 |
您必須擷取這些值,才能使用Windows ML 應用程式顯示正確的預測。
後續步驟
我們的模型已準備好部署。 接下來,到了重頭戲 - 讓我們 建置 Windows 應用程式,並在您的 Windows 裝置上於本機執行。