2017-09-21 5 views
0

私は自分のデータベースとしてtfrecordsを作成しました。データベースは9種類のtfrecordファイルで構成されています。その目的は、9つのデータベースからサンプルのバッチをモデルにフィードすることでした。したがって、私はTFRecordDatasetとジップ関数を使用しています。各サンプルは、フレームとそのフィーチャセットで構成されています。したがって、各tfrecordファイルから8個のサンプルを取る必要があります。合計72個の(features, image)がバッチ内にあります。したがって、以下のコードに示すように、画像だけで特徴を抽出しました。テンソルフローのtf.contrib.data.Datasets APIを使用している時代の終わりにエラーを処理できません

問題:第1エポックの終わりに到達すると、残りのデータは72未満になります。その結果、第2エポックからのデータが72サンプルのバッチを構成するように追加されました。ですから、私はリカレントニューラルネットワークを訓練しているので、私の場合はこれでは解決できません。したがって、私は一貫していなければならない状態があります(今は議論する必要はありません)。

したがって、私はリピート機能を使用せず、https://www.tensorflow.org/programmers_guide/datasetsに記載されているものを実装しようとしています。複数のエポックを処理しています。

# Compute for 100 epochs. 
for _ in range(100): 
    sess.run(iterator.initializer) 
    while True: 
    try: 
     sess.run(next_element) 
    except tf.errors.OutOfRangeError: 
     break 

    # [Perform end-of-epoch calculations here.] 

私がこれをやった後、別の問題が発生しました。まず、ここで私の完全なコードは次のとおりです。

import tensorflow as tf 
import numpy as np 
import time 
import cv2 

num_epoch = 1 
batch_size = 8 # This is set to 8 since 
num_threads = 9 
common = "C:/Users/user/PycharmProjects/AffectiveComputingNew/database/" 
filenames = [(common + "train_1_db.tfrecords"), (common + "train_2_db.tfrecords"), (common + "train_3_db.tfrecords"), 
    (common + "train_4_db.tfrecords"), (common + "train_5_db.tfrecords"), (common + "train_6_db.tfrecords"), 
    (common + "train_7_db.tfrecords"), (common + "train_8_db.tfrecords"), (common + "train_9_db.tfrecords")] 

# Transforms a scalar string `example_proto` into a pair of a scalar string and 
# a scalar integer, representing an image and its label, respectively. 
def _parse_function(example_proto): 
    features = { 
     'height': tf.FixedLenFeature([], tf.int64), 
     'width': tf.FixedLenFeature([], tf.int64), 
     'image_raw': tf.FixedLenFeature([], tf.string), 
     'features': tf.FixedLenFeature([432], tf.float32) 
    } 

    parsed_features = tf.parse_single_example(example_proto, features) 

    # This is how we create one example, that is, extract one example from the database. 
    image = tf.decode_raw(parsed_features['image_raw'], tf.uint8) 
    # The height and the weights are used to 
    height = tf.cast(parsed_features['height'], tf.int32) 
    width = tf.cast(parsed_features['width'], tf.int32) 

    # The image is reshaped since when stored as a binary format, it is flattened. Therefore, we need the 
    # height and the weight to restore the original image back. 
    image = tf.reshape(image, [height, width, 3]) 

    features = parsed_features['features'] 

    return features, image 

random_features = tf.Variable(tf.zeros([72, 432], tf.float32)) 
random_images = tf.Variable(tf.zeros([72, 112, 112, 3])) 

datasets = [] 
for _ in filenames: 
    datasets.append(tf.contrib.data.TFRecordDataset(_).map(_parse_function)) 

dataset_ziped = tf.contrib.data.TFRecordDataset.zip((datasets[0], datasets[1], datasets[2], datasets[3], 
     datasets[4], datasets[5], datasets[6], datasets[7], datasets[8])) 
#dataset = dataset_ziped.repeat(num_epoch) 
dataset = dataset_ziped.batch(batch_size) 

iterator = dataset.make_initializable_iterator() 
next_batch = iterator.get_next() # This has shape: [9, 2] 

features = tf.concat((next_batch[0][0], next_batch[1][0], next_batch[2][0], next_batch[3][0], 
         next_batch[4][0], next_batch[5][0], next_batch[6][0], next_batch[7][0], 
         next_batch[8][0]), axis=0) 
features = tf.reshape(features, shape=[9, 8, 432]) # where 8 * 9 = 72 
features = tf.transpose(features, perm=[1, 0, 2]) # shape becomes: [8, 9, 432] 
features = tf.reshape(features, shape=[72, 432]) # Now frames will be: 1st frame from 1st video, second from second video... 

images = tf.concat((next_batch[0][1], next_batch[1][1], next_batch[2][1], next_batch[3][1], 
        next_batch[4][1], next_batch[5][1], next_batch[6][1], next_batch[7][1], 
        next_batch[8][1]), axis=0) 
images = tf.reshape(images, shape=[9, 8, 112, 112, 3]) 
images = tf.transpose(images, perm=[1, 0, 2, 3, 4]) 
images = tf.reshape(images, shape=[72, 112, 112, 3]) 

init_op = tf.global_variables_initializer() 

with tf.Session() as sess: 
    # Initialize `iterator` with training data. 
    sess.run(init_op) 

    for _ in range(num_epoch): 
     sess.run(iterator.initializer) 

     # This while loop will run indefinitly until the end of the first epoch 
     while True: 
      try: 
       lst = [] 
       features_np = sess.run([features])[0] # since the output is always: (1, 72, 432) 

       for f in features_np: 
        lst.append(f[0]) 

      except tf.errors.OutOfRangeError: 
       print('errorrrrr') 

ので、サンプル数は、もはや72でないので、私はラインでエラーに遭遇:

features = tf.reshape(features, shape=[9, 8, 432]) # where 8 * 9 = 72 

だから、私はこれを処理する方法が必要ですエラー。私はアサーションを次のように試みました:

assert_op = tf.Assert(tf.equal(tf.shape(features[0]), batch_size * 9), [features]) 
with tf.control_dependencies([assert_op])... after features = tf.concat... 

そしてそれはうまくいきませんでした。私は次のようにtf.condみました(そしてそれは同様に動作しませんでした):

結論
tf.cond(tf.equal(tf.shape(features)[0], batch_size * 9), 
     lambda: tf.assign(random_features, features), 
     lambda: tf.assign(random_features, random_features)) 

features = tf.reshape(random_features, shape=[9, 8, 432]) # where 8 * 9 = 72 
.... 

が、私は別の反復からのサンプルをインターリーブすることなく、エポックを反復する方法する必要があり、同時に保持しますreshape機能(バッチサイズが私の場合は72未満)を使用している間に機能の問題。

ご迷惑をおかけして申し訳ありません。

答えて

0

最後のバッチが切り捨てられているため、バッチサイズがコードに指定されたbatch_sizeに等しい場合は、最初のバッチの値が割り当てられる一時的なvariableが作成されました。したがって、現在のバッチのサイズがbatch_sizeに等しくなくなったら、作成した一時バッチを使用しました。ここでは、次の解決策は次のとおりです。

import tensorflow as tf 
import numpy as np 
import time 
import cv2 

num_epoch = 2 
batch_size = 8 # This is set to 8 since 
num_threads = 9 
common = "C:/Users/user/PycharmProjects/AffectiveComputingNew/database/" 
filenames = [(common + "train_1_db.tfrecords"), (common + "train_2_db.tfrecords"), (common + "train_3_db.tfrecords"), 
    (common + "train_4_db.tfrecords"), (common + "train_5_db.tfrecords"), (common + "train_6_db.tfrecords"), 
    (common + "train_7_db.tfrecords"), (common + "train_8_db.tfrecords"), (common + "train_9_db.tfrecords")] 

# Transforms a scalar string `example_proto` into a pair of a scalar string and 
# a scalar integer, representing an image and its label, respectively. 
def _parse_function(example_proto): 
    features = { 
     'height': tf.FixedLenFeature([], tf.int64), 
     'width': tf.FixedLenFeature([], tf.int64), 
     'image_raw': tf.FixedLenFeature([], tf.string), 
     'features': tf.FixedLenFeature([432], tf.float32) 
    } 

    parsed_features = tf.parse_single_example(example_proto, features) 

    # This is how we create one example, that is, extract one example from the database. 
    image = tf.decode_raw(parsed_features['image_raw'], tf.uint8) 
    # The height and the weights are used to 
    height = tf.cast(parsed_features['height'], tf.int32) 
    width = tf.cast(parsed_features['width'], tf.int32) 

    # The image is reshaped since when stored as a binary format, it is flattened. Therefore, we need the 
    # height and the weight to restore the original image back. 
    image = tf.reshape(image, [height, width, 3]) 

    features = parsed_features['features'] 

    return features, image 
# Here is the temp var that I will use whenever the return batch from the dataset doesn't have a size of batch_size * 9 mentioned above. 
random_features = tf.Variable(tf.zeros([72, 432], tf.float32)) 
random_images = tf.Variable(tf.zeros([72, 112, 112, 3], tf.uint8)) 

datasets = [] 
for _ in filenames: 
    datasets.append(tf.contrib.data.TFRecordDataset(_).map(_parse_function)) 

dataset_ziped = tf.contrib.data.TFRecordDataset.zip((datasets[0], datasets[1], datasets[2], datasets[3], 
     datasets[4], datasets[5], datasets[6], datasets[7], datasets[8])) 
dataset = dataset_ziped.batch(batch_size) 

iterator = dataset.make_initializable_iterator() 
next_batch = iterator.get_next() # This has shape: [9, 2] 

features = tf.concat((next_batch[0][0], next_batch[1][0], next_batch[2][0], next_batch[3][0], 
         next_batch[4][0], next_batch[5][0], next_batch[6][0], next_batch[7][0], 
         next_batch[8][0]), axis=0) 
images = tf.concat((next_batch[0][1], next_batch[1][1], next_batch[2][1], next_batch[3][1], 
        next_batch[4][1], next_batch[5][1], next_batch[6][1], next_batch[7][1], 
        next_batch[8][1]), axis=0) 

def get_features(features, images): 
    with tf.control_dependencies([tf.assign(random_features, features), tf.assign(random_images, images)]): 
     features = tf.reshape(features, shape=[9, 8, 432]) # where 8 * 9 = 72 
     features = tf.transpose(features, perm=[1, 0, 2]) # shape becomes: [8, 9, 432] 
     features = tf.reshape(features, shape=[72, 432]) # Now frames will be: 1st frame from 1st video, second from second video... 

     images = tf.reshape(images, shape=[9, 8, 112, 112, 3]) 
     images = tf.transpose(images, perm=[1, 0, 2, 3, 4]) 
     images = tf.reshape(images, shape=[72, 112, 112, 3]) 
     return features, images 

condition1 = tf.equal(tf.shape(features)[0], batch_size * 9) 
condition2 = tf.equal(tf.shape(images)[0], batch_size * 9) 

condition = tf.logical_and(condition1, condition2) 

features, images = tf.cond(condition, 
          lambda: get_features(features, images), 
          lambda: get_features(random_features, random_images)) 

init_op = tf.global_variables_initializer() 

with tf.Session() as sess: 
    # Initialize `iterator` with training data. 
    sess.run(init_op) 

    for _ in range(num_epoch): 
     sess.run(iterator.initializer) 

     # This while loop will run indefinitly until the end of the first epoch 
     while True: 
      try: 
       lst = [] 
       features_np, images_np = sess.run([features, images]) 

       for f in features_np: 
        lst.append(f[0]) 

       print(lst) 
      except tf.errors.OutOfRangeError: 
       print('errorrrrr') 
       break 

データセットをビュンとき、それは要素が9つの異なるデータセットからフェッチされていますサンプルデータを作成しますので、私はいつもbatch_size * 9に言及していることに注意してください。したがって、私はbatch_sizeを8に割り当てて72サンプルを得たので、私は8 * 9をとりました。

関連する問題