【发布时间】:2017-09-23 06:05:32
【问题描述】:
我创建了 tfrecords 作为我的数据库。该数据库由 9 个不同的 tfrecord 文件组成。目的是将 9 个数据库中的一批样本输入到模型中。因此,我使用了TFRecordDataset 的zip 功能。每个样本都包含一个框架及其特征集。因此,我需要从每个 tfrecord 文件中抽取 8 个样本,这样一批中总共有 72 个(features, image)。因此,我只用图像提取了特征,如下面的代码所示。
问题:当我到达 1st epoch 结束时,剩余的数据少于 72。结果,来自第二个 epoch 的数据添加为一批 72 个样本。所以,这在我的情况下是不可取的,因为我正在训练一个循环神经网络,所以我有一个应该是一致的状态(现在不需要讨论)。
因此,我没有使用repeat函数,而是尝试实现https://www.tensorflow.org/programmers_guide/datasets处理多个时期中提到的内容,即使用for循环和try和except。
# 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
....
总之,我需要在不交错来自不同迭代的样本的情况下迭代 epoch,同时在使用 reshape 函数(其中批量大小小于 72 在我的案子)。
非常感谢任何帮助!
【问题讨论】:
标签: python tensorflow batch-processing