Tensorflow:tf-record処理マトリクスまたはテンソルデータの方法および注意事項


このブログを書く鍵Bug:Input to reshape is a tensor with xxx values,but the requested shape has xxx.本稿の先行知識はtensorflowにおけるtfrecordの作成とインポートである.
 

問題の導入


tensorflow featureタイプはlistデータのみを受け入れますが、データタイプがマトリクスまたはテンソルであればどのように処理しますか?
例えば、現在のタスクは、ターゲット検出です.tf-recordに各ピクチャに対応するbounding boxの情報を記録する必要があります.1つのbounding boxの形状は(1,4)であり,それ自体がlistデータであり,直接使用できる.しかし、1枚の画像は複数のbouning boxに対応する可能性があるので、形状は(?,4)であるべきで、これは長くなるので、どのように保存すればいいのでしょうか.保存するbouning boxは次のようになります.
bbox= np.array([[10, 20, 30 ,40],
                [10, 20, 20, 20]])

シナリオ1

  • はlistタイプに変換され、listで
  • に書き込む.
  • 形状情報
  • を記録する.
    #  , float, list, 
    features['bbox'] = tf.train.Feature(float_list=tf.train.FloatList(value=bbox.reshape(-1)))
    features['bbox_shape'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bbox.shape))

    bboxをtfrecordに保存すると、同じように解析する必要があります.コードは以下の通りです.
    dics = {'bbox': tf.VarLenFeature(dtype=tf.float32),
            'bbox_shape': tf.FixedLenFeature(shape=(2,), dtype=tf.int64)}
    
    parsed_example = tf.parse_single_example(example_proto, dics)
    
    #  VarLen bbox, tensor, 
    parsed_example['bbox'] = tf.sparse_tensor_to_dense(parsed_example['bbox'])
    #  shape 
    parsed_example['bbox'] = tf.reshape(parsed_example['bbox'], parsed_example['bbox_shape'])

    シナリオ1では、最初から提示されていたバグには遭遇しませんでした.
     

    シナリオ2

  • で使用する.tostring()テンソルをstringタイプ
  • に変換
  • 形状情報を記録し、
  • の復元を容易にする.
    #  bbox , 
    features['bbox'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[bbox.tostring()]))
    features['bbox_shape'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bbox.shape))

    同様に解析する必要があります
    disc = {'bbox': tf.FixedLenFeature(shape=(), dtype=tf.string),
            'bbox_shape': tf.FixedLenFeature(shape=(2,), dtype=tf.int64)}
    
    parsed_example = tf.parse_single_example(example_proto, dics)
    
    # string tf.decode_raw(parsed_feature, type) , type 
    parsed_example['bbox'] = tf.decode_raw(parsed_example['bbox'], tf.uint16)
    #  
    parsed_example['bbox'] = tf.reshape(parsed_example['bbox'], parsed_example['bbox_shape'])

    注:データフォーマットと解析フォーマットの一致を保証する必要がある.
    元データがtf.float32種類からto_bytes種類の書き込みを行う場合、tf.decode_raw復号時にもtf.float32種類のデータが必要となる.
    一致しない場合は、Input to reshape is a tensor with xxx values, but the requested shape has xxx と同様のエラーが発生します.私のbboxはtfですuint 16タイプが書き込むので、解析時にtfを使用する必要がある.uint16.

     


    まとめ


    このブログでは、Bugを通じて問題を導入し、Bugの出所と処理方法を詳しく説明し、皆さんの役に立つことを望んでいます.もし皆さんが依然として似たような問題に遭遇したら、伝言を残して、定期的に返事することができます!
    備考:本文は作者のオリジナルで、転載は出典を明記する必要があります!