序列化

儲存模型和任何 Proto 類別

此 ONNX 圖表需要序列化為一個連續的記憶體緩衝區。方法 SerializeToString 在每個 ONNX 物件中都可用。

with open("model.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

此方法具有以下簽名。

class onnx.ModelProto
SerializeToString()

將訊息序列化為字串,僅適用於已初始化的訊息。

每個 Proto 類別都實作了方法 SerializeToString。因此,以下程式碼適用於頁面 Protos 中描述的任何類別。

with open("proto.pb", "wb") as f:
    f.write(proto.SerializeToString())

下一個範例顯示如何儲存 NodeProto

from onnx import NodeProto

node = NodeProto()
node.name = "example-type-proto"
node.op_type = "Add"
node.input.extend(["X", "Y"])
node.output.extend(["Z"])

with open("node.pb", "wb") as f:
    f.write(node.SerializeToString())

載入模型

以下函式僅自動化載入類別 ModelProto。下一個章節顯示如何還原任何其他 proto 類別。

onnx.load(f: IO[bytes] | str | PathLike, format: Literal['protobuf', 'textproto', 'onnxtxt', 'json'] | str | None = None, load_external_data: bool = True) ModelProto

將序列化的 ModelProto 載入記憶體。

參數:
  • f – 可以是類檔案物件 (具有「read」函式) 或包含檔案名稱的字串/PathLike

  • format – 序列化格式。當未指定時,會從檔案副檔名推斷 (當 f 為路徑時)。如果未指定 _且_ f 不是路徑,則會使用「protobuf」。當格式為文字格式時,會假設編碼為「utf-8」。

  • load_external_data – 是否載入外部資料。如果資料與模型位於同一目錄下,請設定為 True。否則,使用者需要呼叫 load_external_data_for_model() 並提供目錄以從中載入外部資料。

傳回值:

載入記憶體的 ModelProto。

from onnx import load

onnx_model = load("model.onnx")

Or

from onnx import load

with open("model.onnx", "rb") as f:
    onnx_model = load(f)

下一個函式從位元組陣列執行相同的操作。

onnx.load_model_from_string(s: bytes | str, format: Literal['protobuf', 'textproto', 'onnxtxt', 'json'] | str = 'protobuf') ModelProto[來源]

載入包含序列化 ModelProto 的二進位字串 (位元組)。

參數:
  • s – 包含序列化 ModelProto 的字串

  • format – 序列化格式。當未指定時,會從檔案副檔名推斷 (當 f 為路徑時)。如果未指定 _且_ f 不是路徑,則會使用「protobuf」。當格式為文字格式時,會假設編碼為「utf-8」。

傳回值:

載入記憶體的 ModelProto。

載入 Proto

此處的 Proto 指的是包含資料的任何類型,包括模型、張量、稀疏張量、頁面 Protos 中列出的任何類別。使用者必須知道他需要還原的資料類型,然後呼叫方法 ParseFromStringprotobuf 不會儲存有關儲存資料類別的任何資訊。因此,必須先知道此類別,然後才能還原物件。

class onnx.ModelProto
ParseFromString()

將序列化訊息剖析到目前的訊息中。

下一個範例顯示如何還原 NodeProto

from onnx import NodeProto

tp2 = NodeProto()
with open("node.pb", "rb") as f:
    content = f.read()

tp2.ParseFromString(content)

print(tp2)
input: "X"
input: "Y"
output: "Z"
name: "example-type-proto"
op_type: "Add"

存在 TensorProto 的捷徑

onnx.load_tensor_from_string(s: bytes, format: Literal['protobuf', 'textproto', 'onnxtxt', 'json'] | str = 'protobuf') TensorProto[原始碼]

載入包含序列化 TensorProto 的二進制字串 (bytes)。

參數:
  • s – 一個包含序列化 TensorProto 的字串。

  • format – 序列化格式。當未指定時,會從檔案副檔名推斷 (當 f 為路徑時)。如果未指定 _且_ f 不是路徑,則會使用「protobuf」。當格式為文字格式時,會假設編碼為「utf-8」。

傳回值:

載入記憶體中的 TensorProto。