2017-05-18 15 views
0

目的はTfRecordsのデータベースを作成することでした。 私はそれぞれ7500イメージを含む23のフォルダと23のテキストファイルを持っていて、それぞれ7500イメージの機能を説明する7500行が別々のフォルダにあります。文字列のリストからTfRecordsを作成し、デコード後にテンソルフローでグラフを供給

私はこのコードを介してデータベースを作成した:

したがって
import tensorflow as tf 
import numpy as np 
from PIL import Image 

def _Float_feature(value): 
    return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) 

def _bytes_feature(value): 
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) 

def _int64_feature(value): 
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) 

def create_image_annotation_data(): 
    # Code to read images and features. 
    # images represent a list of numpy array of images, and features_labels represent a list of strings 
    # where each string represent the whole set of features for each image. 
    return images, features_labels 

# This is the starting point of the program. 
# Now I have the images stored as list of numpy array, and the features as list of strings. 
images, annotations = create_image_annotation_data() 

tfrecords_filename = "database.tfrecords" 
writer = tf.python_io.TFRecordWriter(tfrecords_filename) 

for img, ann in zip(images, annotations): 

    # Note that the height and width are needed to reconstruct the original image. 
    height = img.shape[0] 
    width = img.shape[1] 

    # This is how data is converted into binary 
    img_raw = img.tostring() 
    example = tf.train.Example(features=tf.train.Features(feature={ 
     'height': _int64_feature(height), 
     'width': _int64_feature(width), 
     'image_raw': _bytes_feature(img_raw), 
     'annotation_raw': _bytes_feature(tf.compat.as_bytes(ann)) 
    })) 

    writer.write(example.SerializeToString()) 

writer.close() 

reconstructed_images = [] 

record_iterator = tf.python_io.tf_record_iterator(path=tfrecords_filename) 

for string_record in record_iterator: 
    example = tf.train.Example() 
    example.ParseFromString(string_record) 

    height = int(example.features.feature['height'] 
       .int64_list 
       .value[0]) 

    width = int(example.features.feature['width'] 
       .int64_list 
       .value[0]) 

    img_string = (example.features.feature['image_raw'] 
        .bytes_list 
        .value[0]) 

    annotation_string = (example.features.feature['annotation_raw'] 
         .bytes_list 
         .value[0]) 

    img_1d = np.fromstring(img_string, dtype=np.uint8) 
    reconstructed_img = img_1d.reshape((height, width, -1)) 
    annotation_reconstructed = annotation_string.decode('utf-8') 

をtfRecordsに画像やテキストを変換した後、それらを読み、Pythonで文字列にnumpyの及び(バイナリテキスト)に画像を変換することができる後、私は余分なマイルをfilename_queueを読者で使用してみようとしました(目的は一度に1つのデータではなく、バッチのデータをグラフに提供することでした)。したがって、ネットワークをより早くトレーニングすることができます)

したがって、私はfollコード: OutOfRangeError(トレースバックについては上記参照):最後に

import tensorflow as tf 
import numpy as np 
import time 

image_file_list = ["database.tfrecords"] 
batch_size = 16 

# Make a queue of file names including all the JPEG images files in the relative 
# image directory. 
filename_queue = tf.train.string_input_producer(image_file_list, num_epochs=1, shuffle=False) 

reader = tf.TFRecordReader() 

# Read a whole file from the queue, the first returned value in the tuple is the 
# filename which we are ignoring. 
_, serialized_example = reader.read(filename_queue) 

features = tf.parse_single_example(
     serialized_example, 
     # Defaults are not specified since both keys are required. 
     features={ 
      'height': tf.FixedLenFeature([], tf.int64), 
      'width': tf.FixedLenFeature([], tf.int64), 
      'image_raw': tf.FixedLenFeature([], tf.string), 
      'annotation_raw': tf.FixedLenFeature([], tf.string) 
     }) 

image = tf.decode_raw(features['image_raw'], tf.uint8) 
annotation = tf.decode_raw(features['annotation_raw'], tf.float32) 

height = tf.cast(features['height'], tf.int32) 
width = tf.cast(features['width'], tf.int32) 

image = tf.reshape(image, [height, width, 3]) 

# Note that the minimum after dequeue is needed to make sure that the queue is not empty after dequeuing so that 
# we don't run into errors 
''' 
min_after_dequeue = 100 
capacity = min_after_dequeue + 3 * batch_size 
ann, images_batch = tf.train.batch([annotation, image], 
            shapes=[[1], [112, 112, 3]], 
            batch_size=batch_size, 
            capacity=capacity, 
            num_threads=1) 
''' 

# Start a new session to show example output. 
with tf.Session() as sess: 
    merged = tf.summary.merge_all() 
    train_writer = tf.summary.FileWriter('C:/Users/user/Documents/tensorboard_logs/New_Runs', sess.graph) 

    # Required to get the filename matching to run. 
    tf.global_variables_initializer().run() 

    # Coordinate the loading of image files. 
    coord = tf.train.Coordinator() 
    threads = tf.train.start_queue_runners(coord=coord) 

    for steps in range(16): 
     t1 = time.time() 
     annotation_string, batch, summary = sess.run([annotation, image, merged]) 
     t2 = time.time() 
     print('time to fetch 16 faces:', (t2 - t1)) 
     print(annotation_string) 
     tf.summary.image("image_batch", image) 
     train_writer.add_summary(summary, steps) 

    # Finish off the filename queue coordinator. 
    coord.request_stop() 
    coord.join(threads) 

は、上記のコードを実行した後、私は次のようなエラーだFIFOQueue「_0_input_producer」閉じられているのと持って不十分要素は、(1、現在のサイズを要求しました0) [ノード:ReaderReadV2 = ReaderReadV2 [_device = "/ジョブ:ローカルホスト/レプリカ:0 /タスク:0/CPU:0"(TFRecordReaderV2、input_producer)]]

別の質問:

  1. バイナリデータベース(tfrecords)をデコードして、 "python文字列データ構造体"として保存されたフィーチャを取り戻す方法。
  2. tf.train.batchを使用して、ネットワークに供給するためのバッチの例を作成する方法。

ありがとうございました! 何か助けていただければ幸いです。

答えて

1

この問題を解決するために、queue runnerと一緒にcoordinatorSessionの範囲内で初期化する必要がありました。さらに、エポックの数は内部的に制御されるため、global variableではなく、local variableと考えてください。したがって、queue_runnerにをQueueにエンキューするように指示する前に、そのローカル変数を初期化する必要があります。したがって、次のコードは次のとおりです。

filename_queue = tf.train.string_input_producer(tfrecords_filename, num_epochs=num_epoch, shuffle=False, name='queue') 
reader = tf.TFRecordReader() 

key, serialized_example = reader.read(filename_queue) 
features = tf.parse_single_example(
    serialized_example, 
    # Defaults are not specified since both keys are required. 
    features={ 
     'height': tf.FixedLenFeature([], tf.int64), 
     'width': tf.FixedLenFeature([], tf.int64), 
     'image_raw': tf.FixedLenFeature([], tf.string), 
     'annotation_raw': tf.FixedLenFeature([], tf.string) 
    }) 
... 
init_op = tf.group(tf.local_variables_initializer(), 
       tf.global_variables_initializer()) 
with tf.Session() as sess: 
    sess.run(init_op) 

    coord = tf.train.Coordinator() 
    threads = tf.train.start_queue_runners(coord=coord) 

これで動作するはずです。

ネットワークに画像を送る前に一式の画像を収集するには、tf.train.shuffle_batchまたはtf.train.batchを使用できます。両方の作品。違いは簡単です。 1つは画像をシャッフルし、もう1つはシャッフルしません。ただし、スレッド数を定義してtf.train.batchを使用すると、エンキューされているスレッド間で競合が発生するので、データサンプルをシャッフルする可能性があります。file_namesとにかく、次のコードは次のようにQueueを初期化した後に直接挿入されるべきである:ここでtensorsの形状が異なっていてもよい

min_after_dequeue = 100 
num_threads = 1 
capacity = min_after_dequeue + num_threads * batch_size 
label_batch, images_batch = tf.train.batch([annotation, image], 
             shapes=[[], [112, 112, 3]], 
             batch_size=batch_size, 
             capacity=capacity, 
             num_threads=num_threads) 

注意。読者がサイズ[112, 112, 3]のカラー画像をデコードしていたことが起こりました。注釈には[]があります(理由はありませんが、それは特別なケースでした)。

最後に、tf.stringデータ型を文字列として扱うことができます。実際には、注釈テンソルを評価した後、テンソルはbinary stringとして扱われることがわかります(これが実際にテンソルフローで扱われる方法です)。したがって、私の場合、文字列はその特定の画像に関連する一連の機能に過ぎませんでした。したがって、特定の機能を抽出するには、次の例を参考にしてください:

# The output of string_split is not a tensor, instead, it is a SparseTensorValue. Therefore, it has a property value that stores the actual values. as a tensor. 
label_batch_splitted = tf.string_split(label_batch, delimiter=', ') 
label_batch_values = tf.reshape(label_batch_splitted.values, [batch_size, -1]) 
# string_to_number will convert the feature's numbers into float32 as I need them. 
label_batch_numbers = tf.string_to_number(label_batch_values, out_type=tf.float32) 
# the tf.slice would extract the necessary feature which I am looking. 
confidences = tf.slice(label_batch_numbers, begin=[0, 3], size=[-1, 1]) 

関連する問題