【问题标题】:Protobuf json_format changes datatype from int to floatProtobuf json_format 将数据类型从 int 更改为 float
【发布时间】:2023-01-28 06:49:00
【问题描述】:

我有一个像这样的 python 字典:

{'class_name': 'InputLayer',
 'config': {'batch_input_shape': (None, 32),
  'dtype': 'float32',
  'sparse': False,
  'ragged': False,
  'name': 'input_5'}}

当我尝试使用 json_format 方法将其转换为 protobuf 消息时,它会将 config.batch_input_shape 32int 数据类型更改为 float 32.0

转换使用的代码(layer_config就是上面的dict):

import json
from google.protobuf import json_format
from google.protobuf import struct_pb2 as struct

json_format.Parse(json.dumps(layer_config), struct.Struct())

有什么方法可以避免从 intfloat 的这种类型转换?

我还尝试使用 update 方法进行转换,如下所示:

s = Struct()
s.update(layer_config)

但随后它也会转换类型。

【问题讨论】:

    标签: python json protocol-buffers


    【解决方案1】:

    根据初步研究,由于数字在 Python 中的转换方式,这不是相对容易解决的问题

    protobufs/well_known_types.py 有一个方法 _SetStructValue 进行类型转换,在我们处理数字的地方,我们正在对 floatint 进行类型检查。

    def _SetStructValue(struct_value, value):
      if value is None:
        struct_value.null_value = 0
      elif isinstance(value, bool):
        # Note: this check must come before the number check because in Python
        # True and False are also considered numbers.
        struct_value.bool_value = value
      elif isinstance(value, str):
        struct_value.string_value = value
      elif isinstance(value, (int, float)):
        struct_value.number_value = value
      elif isinstance(value, (dict, Struct)):
        struct_value.struct_value.Clear()
        struct_value.struct_value.update(value)
      elif isinstance(value, (list, ListValue)):
        struct_value.list_value.Clear()
        struct_value.list_value.extend(value)
      else:
        raise ValueError('Unexpected type')
    

    一种可能的解决方案是我们遍历有效负载对象图并执行必要的类型转换以根据需要了解类型。

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 2022-01-06
      • 1970-01-01
      • 2013-08-31
      • 2019-12-06
      • 2015-07-31
      • 2019-12-06
      • 2021-03-04
      • 2020-12-31
      相关资源
      最近更新 更多