TFDV Tensorflow 数据验证:我如何 save/load protobuf 模式 to/from 文件

TFDV Tensorflow Data Validation: how can I save/load the protobuf schema to/from a file

TFDV 将模式生成为模式协议缓冲区。但是,write/read 架构 to/from 文件似乎没有辅助函数。

schema = tfdv.infer_schema(stats)

如何保存 it/load 它?

您可以使用以下方法write/load 架构 to/from 文件。

from google.protobuf import text_format
from tensorflow.python.lib.io import file_io
from tensorflow_metadata.proto.v0 import schema_pb2

def write_schema(schema, output_path):
  schema_text = text_format.MessageToString(schema)
  file_io.write_string_to_file(output_path, schema_text)

def load_schema(input_path):
  schema = schema_pb2.Schema()
  schema_text = file_io.read_file_to_string(input_path)
  text_format.Parse(schema_text, schema)
  return schema      

如果您要将它与 Tensorflow Transform 一起使用,那么我建议使用以下函数:

import tensorflow_data_validation as tfdv
from tensorflow.python.lib.io import file_io
from tensorflow_transform.tf_metadata import metadata_io

# Define file path
file_io.recursive_create_dir(OUTPUT_DIR)
schema_file = os.path.join(OUTPUT_DIR, 'schema.pbtxt')

# Write schema
tfdv.write_schema_text(schema, schema_file)

# Read schema with tfdv
schema = tfdv.load_schema_text(schema_file)

# Read schema with tensorflow_transform
schema = metadata_io.read_metadata(OUTPUT_DIR)

输出是人类可读的——类似于JSON。但是,如果您更喜欢以纯 JSON 格式 保存它,那么您可以使用以下内容:

from google.protobuf import json_format
from tensorflow.python.lib.io import file_io
from tensorflow_metadata.proto.v0 import schema_pb2

def write_schema(schema, output_path):
    schema_text = json_format.MessageToJson(schema)
    file_io.write_string_to_file(output_path, schema_text)

def load_schema(input_path):
    schema_text = file_io.read_file_to_string(input_path)
    schema = json_format.Parse(schema_text, schema_pb2.Schema())
    return schema   

或者,如果您不需要它采用人类可读的格式,您可以使用 SerializeToString() 和 ParseFromString(data) for de/serialization,如 here.

所述

tensorflow_data_validation 本身为您提供实用函数:

from tensorflow_data_validation.utils.schema_util import write_schema_text, load_schema_text
write_schema_text(schema, "./my_schema")
schema = load_schema_text("./my_schema")