model {
faster_rcnn {
num_classes: 37
image_resizer {
keep_aspect_ratio_resizer {
min_dimension: 600
max_dimension: 1024
}
}
...
我希望使用 python 将其读入对象,对某些值进行一些更改,然后将其写回配置文件。
一个复杂的因素是这是一个相当大的对象,它由许多 .proto 文件构成。
我能够通过将 protobuf 转换为字典、进行编辑然后转换回 protobuf 来完成任务,如下所示:
import tensorflow as tf
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
from google.protobuf import text_format
from object_detection.protos import pipeline_pb2
def get_configs_from_pipeline_file(pipeline_config_path, config_override=None):
'''
read .config and convert it to proto_buffer_object
'''
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.gfile.GFile(pipeline_config_path, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, pipeline_config)
if config_override:
text_format.Merge(config_override, pipeline_config)
return pipeline_config
configs = get_configs_from_pipeline_file('faster_rcnn_resnet101_pets.config')
d = MessageToDict(configs)
d['model']['fasterRcnn']['numClasses']=999
config2 = pipeline_pb2.TrainEvalPipelineConfig()
c = ParseDict(d, config2)
s = text_format.MessageToString(c)
with open('/path/test.config', 'w+') as fh:
fh.write(str(s))
我希望能够直接对 protobuf 对象进行编辑,而无需转换为字典。然而,问题是不清楚如何“走 dom”以发现对我想更改其值的变量的正确引用。当涉及多个 .proto 文件时尤其如此。
我能够像这样进行编辑,但我希望有更好的方法:
configs.model.ListFields()[0][1].num_classes = 99