【问题标题】:How to read json files in Tensorflow?如何在 Tensorflow 中读取 json 文件?
【发布时间】:2016-07-14 18:42:54
【问题描述】:

我正在尝试编写一个函数,在 tensorflow 中读取 json 文件。 json 文件具有以下结构:

{
    "bounding_box": {
        "y": 98.5, 
        "x": 94.0, 
        "height": 197, 
        "width": 188
     }, 
    "rotation": {
        "yaw": -27.97019577026367,
        "roll": 2.206029415130615, 
        "pitch": 0.0}, 
        "confidence": 3.053506851196289, 
        "landmarks": {
            "1": {
                "y": 180.87722778320312, 
                "x": 124.47326660156205}, 
            "0": {
                "y": 178.60653686523438, 
                "x": 183.41931152343795}, 
            "2": {
                "y": 224.5936889648438, 
                "x": 141.62365722656205
}}}

我只需要边界框信息。有几个关于如何编写read_and_decode-functions的示例,我正在尝试将这些示例转换为json文件的函数,但仍有很多问题......:

def read_and_decode(filename_queue):

  reader = tf.WhichKindOfReader() # ??? 
  _, serialized_example = reader.read(filename_queue)
  features = tf.parse_single_example( 
      serialized_example,

      features={

          'bounding_box':{ 

              'y': tf.VarLenFeature(<whatstheproperdatatype>) ???
              'x': 
              'height': 
              'width': 

          # I only need the bounding box... - do I need to write 
          # the format information for the other features...???

          }
      })

  y=tf.decode() # decoding necessary?
  x=
  height=
  width= 

  return x,y,height,width

我已经在互联网上做了几个小时的研究,但找不到任何关于如何在 tensorflow 中读取 json 的详细信息......

也许有人可以给我一个线索...

【问题讨论】:

    标签: python json neural-network tensorflow


    【解决方案1】:

    更新

    下面的解决方案确实可以完成工作,但效率不高,详情请参阅 cmets。

    原答案

    如果你用tf.py_func包装函数,你可以在TensorFlow中使用标准的python json解析:

    import json
    import numpy as np
    import tensorflow as tf
    
    def get_bbox(str):
        obj = json.loads(str.decode('utf-8'))
        bbox = obj['bounding_box']
        return np.array([bbox['x'], bbox['y'], bbox['height'], bbox['width']], dtype='f')
    
    def get_multiple_bboxes(str):
        return [[get_bbox(x) for x in str]]
    
    raw = tf.placeholder(tf.string, [None])
    [parsed] = tf.py_func(get_multiple_bboxes, [raw], [tf.float32])
    

    注意tf.py_func 返回一个张量列表 而不仅仅是一个张量,这就是为什么我们需要将parsed 包装在一个列表[parsed] 中。如果不是,parsed 将获得形状 [1, None, 4] 而不是所需的形状 [None, 4](其中 None 是批量大小)。

    使用您的数据,您会得到以下结果:

    json_string = """{
        "bounding_box": {
            "y": 98.5,
            "x": 94.0,
            "height": 197,
            "width": 188
         },
        "rotation": {
            "yaw": -27.97019577026367,
            "roll": 2.206029415130615,
            "pitch": 0.0},
            "confidence": 3.053506851196289,
            "landmarks": {
                "1": {
                    "y": 180.87722778320312,
                    "x": 124.47326660156205},
                "0": {
                    "y": 178.60653686523438,
                    "x": 183.41931152343795},
                "2": {
                    "y": 224.5936889648438,
                    "x": 141.62365722656205
    }}}"""
    my_data = np.array([json_string, json_string, json_string])
    
    init_op = tf.initialize_all_variables()
    with tf.Session() as sess:
        sess.run(init_op)
        print(sess.run(parsed, feed_dict={raw: my_data}))
        print(sess.run(tf.shape(parsed), feed_dict={raw: my_data}))
    
    [[  94.    98.5  197.   188. ]
     [  94.    98.5  197.   188. ]
     [  94.    98.5  197.   188. ]]
    [3 4]
    

    【讨论】:

    • 虽然这行得通,但您必须担心 GIL。
    • @TimZaman 我不知道such a thing 存在。你介意详细说明一下吗?我的解决方案最糟糕的情况是什么?
    • 长话短说,python 代码中的每一行都会在运行时阻止要执行的任何其他 python 代码行。这意味着您的 py_func 不能与任何其他 python 代码同时运行,除非您避免使用 GIL。
    • @TimZaman 训练前将所有的json对象预处理成TFRecords,存储在磁盘上,训练时分批读取会更好吗? tf.TFRecordReaderwritten in C++,因此避免使用 GIL,对吗?谢谢你告诉我!
    • 是的,实际上效果会很好。或者,您可以将标签准备为,并将它们放入 tf.constant() 数组或变量中,然后从那里获取。
    【解决方案2】:

    这可能会绕过这个问题,但您可以使用https://stedolan.github.io/jq/tutorial/ 之类的命令行工具将数据预处理为基于行的数据格式,例如 csv。可能也会更有效率。

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 2019-03-20
      • 2018-02-11
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多