如何在tensorflow中实现图像序列滑动窗口?

2024-04-28 20:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文

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

问题

如何将输入的特征字符串重塑为一定长度的序列,例如将1000图像放入一个序列中,然后对这些序列执行窗口化,例如使用窗口移位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()

如果是


Tags: 图像imagedatasizelabelsparsetfbatch
1条回答
网友
1楼 · 发布于 2024-04-28 20:49:16

我设法通过过滤那些越过边界的窗户来做到这一点。一旦你有了解析过的特性,对所有的东西应用窗口化,然后计算哪些窗口溢出并过滤掉:

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%,则会有多个窗口溢出到下一个集合中,因此需要多个过滤器)。在

相关问题 更多 >