【问题标题】:How to add time step dimension to generated batch by tf.data.Dataset API如何通过 tf.data.Dataset API 为生成的批次添加时间步长维度
【发布时间】:2020-08-04 10:54:54
【问题描述】:

我想在批量生成中添加时间步长维度。

目前我在做

train_ds = tf.data.Dataset.\
    from_tensor_slices((x_train, y_train)).\
    shuffle(10000).\
    batch(32)

并获得大小为(32, feature_vector_length)的批次

我想将 time_step_dimention 添加到我的批次中以拥有(batch_size,time_stemp,feature_vector_length)

如何使用tf.data 做圆顶?

【问题讨论】:

  • 我认为您正在寻找的是.window 函数。

标签: python tensorflow keras tensorflow2.0 tf.data.dataset


【解决方案1】:

您可以使用tf.data.Dataset().zip().window() 方法进行输入和输出。

import tensorflow as tf
import numpy as np

x_train = np.random.rand(1000, 5)
y_train = np.sum(x_train, axis=1)

x = tf.data.Dataset.from_tensor_slices(x_train).\
    window(size=3, shift=1, stride=1, drop_remainder=True).\
    flat_map(lambda l: l.batch(3))

y = tf.data.Dataset.from_tensor_slices(y_train)

ds = tf.data.Dataset.zip((x, y)).batch(2, drop_remainder=True)

for xx, yy in ds:
    print(xx, yy)
    break
tf.Tensor(
[[[0.85339111 0.00937855 0.6432005  0.31875691 0.83835893]
  [0.91914805 0.13469408 0.40381527 0.80296816 0.4389627 ]
  [0.40326491 0.28575999 0.86602507 0.40515333 0.35390637]]
 [[0.91914805 0.13469408 0.40381527 0.80296816 0.4389627 ]
  [0.40326491 0.28575999 0.86602507 0.40515333 0.35390637]
  [0.00197349 0.46558597 0.66426367 0.00787106 0.07879078]]], shape=(2, 3, 5), 
    dtype=float64) tf.Tensor([2.663086   2.69958826], shape=(2,), dtype=float64)

这是 5 个特征及其各自目标的 3 个时间步长的 2 个张量。

【讨论】:

  • 很好的例子。然而,我注意到 Y 目标对应于窗口中 3 个 X 输入中的第一个。在大多数情况下,您可能希望它们成为最后一个的目标。但这很容易在 zip 之前使用 y = y.skip(2) 修复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多