用于时间序列分类的Tensorflow数据集API

问题描述 投票:0回答:2

我习惯了新的数据集API,并尝试进行一些时间序列分类。我有一个格式为tf-records的数据集,其形状为:(time_steps x features)。我每个时间步都有一个标签。 (time_steps x 1)

我想要做的是重新格式化数据集,以便有一个如下所示的时间步骤的滚动窗口:(n x windows_size x features)。使用n是time_steps-window_size的数量(如果我在滚动窗口中使用1的步幅)

标签应该是(window_size x 1),这意味着我们采用窗口中最后一个time_step的标签。

我已经知道,我可以使用tf.sliding_window_batch()为这些功能创建滑动窗口。但是,标签的形状是相同的,我不知道如何正确地做到这一点:(n x window_size x 1

如何使用tensorflow数据集API执行此操作? https://www.tensorflow.org/programmers_guide/datasets

谢谢你的帮助!

python tensorflow tensorflow-datasets
2个回答
1
投票

我有一个TF 1.13的慢速解决方案。

    WIN_SIZE= 5000

dataset_input = tf.data.Dataset.from_tensor_slices(data1).window(size= WIN_SIZE,
                                                             shift= WIN_SIZE,
                                                             drop_remainder= False).flat_map(lambda x: 
                                                                                            x.batch(WIN_SIZE))

dataset_label = tf.data.Dataset.from_tensor_slices(data2).window(size= WIN_SIZE,
                                                             shift= WIN_SIZE,
                                                             drop_remainder= False).flat_map(lambda x: 
                                                                                            x.batch(WIN_SIZE)).map(lambda x:
                                                                                                                  x[-1])
dataset= tf.data.Dataset.zip((dataset_input, dataset_label))
dataset= dataset.repeat(1)
data_iter = dataset.make_one_shot_iterator() # create the iterator
next_sample= data_iter.get_next()

with tf.Session() as sess:
    i=0
    while True:
        try:
            r_= sess.run(next_sample)
            i+=1
            print(i)
            print(r_)
            print(r_[0].shape)
            print(r_[1].shape)

        except tf.errors.OutOfRangeError:
            print('end')
            break

我说“慢速解决方案”的原因可能是下面的代码片段可以优化,我还没有完成:

dataset_label = tf.data.Dataset.from_tensor_slices(data2).window(size= WIN_SIZE,
                                                         shift= WIN_SIZE,
                                                         drop_remainder= False).flat_map(lambda x: 
                                                                                        x.batch(WIN_SIZE)).map(lambda x:
                                                                                                              x[-1])

一个有前景的解决方案可能会找到一些“跳过”操作来跳过dataset_label中的无用值,而不是使用“窗口”操作(现在是)。


0
投票

我无法弄清楚如何做到这一点,但我想我也可以用numpy来做。

我找到了这个伟大的answer并将其应用于我的案例。

之后它只是像这样使用numpy:

train_df2 = window_nd(train_df, 50, steps=1, axis=0)
train_features = train_df2[:,:,:-1]
train_labels = train_df2[:,:,-1:].squeeze()[:,-1:]
train_labels.shape

我的标签是最后一栏,因此您可能需要稍微调整一下。

© www.soinside.com 2019 - 2024. All rights reserved.