繁体   English   中英

如何在tensorflow中实现图像(2D数组)序列滑动窗口?

[英]How to implement an image(2D array) sequence sliding window in tensorflow?

上下文

我们有存储在.tfrecord文件中的数据, X是我们的训练数据> 40x40灰度图像和Y :是标签。 这些图像按顺序排序(顺序很重要)。 我们希望使用Tensorflows Estimator API输入这些图像,以使用GoogleML训练具有各种时间窗口大小和移位的神经网络模型(例如:LSTM)。

如何将输入的特征串重新整形为一定长度的序列,例如将1000图像放入一个序列中,然后对这些序列进行窗口化,例如获取50图像的窗口,窗口移位25

当前状态

我们设法实现了这个(下面的稀疏示例),没有第一次重塑为1000个长度集,但结果是从一组的元素975到下一个元素25的窗口,我们不想要 我们需要重叠的窗口,从每组1000图像的开始到结束,但不得越过它们的边界。

import tensorflow as tf

# .tfrecord file consisting of data 'X' and labels 'Y'
dataset = tf.data.TFRecordDataset('.tfrecord file')

# define parse function for dataset.map function
def _parse_function(proto):
    # define constants for parsing
    image_size = 40
    num_channels = 1
    num_classes = 3


    # define your tfrecord feature keys and 
    # reshape 1D arrays into 2D arrays (images)
    keys_to_features = {'X': tf.FixedLenFeature([image_size, image_size, num_channels], tf.float32),  # image height, image width, num_channels
                    'Y': tf.FixedLenFeature([], tf.int64)}

    # Load one example
    parsed_features = tf.parse_single_example(proto, keys_to_features)

    # extract image and labels
    image = parsed_features['X']
    labels = tf.cast( parsed_features['Y'], tf.int32 )
    labels = tf.one_hot( labels, depth=num_classes )  # one hot encoding

    return image, labels

# reshape the data into parse format
dataset = dataset.map(_parse_function)

# define dataset parameters
window_size = 50
batch_size = 500
window_shift = int( window_size / 2 )  # 25

# implement sliding window 
dataset = dataset.window(size=window_size, shift=window_shift, drop_remainder=True ).flat_map( lambda x: x.batch(window_size) )

# batch the data
dataset = dataset.batch(batch_size)

# create an iterator
# iterator = dataset.make_one_shot_iterator().get_next()

上面的iterator将为X数据返回一个形状的张量(batch_size,window_size,image_height,image_width,通道数),在我们的例子中(500, 50, 40, 40, 1) 500,50,40,40,1 (500, 50, 40, 40, 1)Y作为(500, 3) 500,3 (500, 3)数组。

我设法通过过滤掉跨越边界的窗口来做到这一点。 获得解析后的功能后,对所有内容应用窗口,然后计算哪些窗口溢出并过滤掉它们:

ds = tf.data.TFRecordDataset( filename )
ds = ds.map( _parse_function )

# apply windowing
ds = ds.window( size=50, shift=25, drop_remainder=True ).flat_map( lambda x, y: tf.data.Dataset.zip( (x.batch(50), y.batch(50)) ) )
# enumerate dataset and filter every 40th window
ds = ds.apply( tf.data.experimental.enumerate_dataset(start=1) ).filter( lambda i, x: tf.not_equal( i % 40, 0) )
# get rid of enumerations
ds = ds.map( lambda i, x: x )

# batching, shuffling etc...
...

澄清:滤出是每隔40个窗口,因为如果你有1000个窗口和25个窗口移位,那么将有set_len / win_shift = 40窗口,最后一个(即第40个)将溢出到下一个窗口。 另请注意,枚举从1开始,因此不会取出第0个样本,因为0 % x == 0

请注意,这更像是一个黑客而不是一个真正的解决方案。 它与50%的重叠效果很好,但在其他百分比下,计算要丢弃的指数变得更加复杂(如果重叠> 50%,则多个窗口会溢出到下一个集合中,因此需要多个过滤器)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM