gpt4 book ai didi

python - 使用 TensorFlow Dataset api 导入可变长度的输入/输出对

转载 作者:行者123 更新时间:2023-12-01 07:21:21 25 4
gpt4 key购买 nike

我有一组输入/输出对,我想将其用作 RNN 模型的训练示例。因此每个输入/输出都是一个由整数 id 组成的相同长度的列表。因此 3 个训练示例可能如下所示

[
[[1,5,3,2],[22,5,3,8]],
[[2,3],[4,7]],
[[5,4,8,9,2,1,3],[32,4,7,4,5,21,33]]
]

我的问题是如何将此类数据加载到 TensorFlow 数据集中,以便将其提供给下游模型?

我已经尝试过 tf.data.Dataset.from_tensor_slices()方法,但是似乎所有输入和输出都必须具有相同的长度才能使用此方法。但是,正如您从上面的示例中看到的,我的输入和输出的长度是可变的。

答案是填充示例,使它们具有相同的长度,然后使用 tf.data.Dataset.from_tensor_slices() ?如果是这样,是否有 TensorFlow 辅助函数可以执行此操作,或者我应该手动执行此操作?

最佳答案

利用 tf.data 的生成器和 padded_batch 概念来克服可变大小的输入。

import tensorflow as tf
tf.enable_eager_execution()

data = [
[[1,5,3,2],[22,5,3,8]],
[[2,3],[4,7]],
[[5,4,8,9,2,1,3],[32,4,7,4,5,21,33]]
]

data_in = [x for x, y in data]
data_out = [y for x, y in data]

def gen_series():
index_at = 0
while True:
yield data_in[index_at], data_out[index_at]
index_at += 1
if index_at >= len(data):
index_at = 0

ds_series = tf.data.Dataset.from_generator(
gen_series,
output_types=(tf.int32, tf.int32),
output_shapes = ((None, None)))

BATCH_SIZE = 2
ds_series_batch = ds_series.padded_batch(BATCH_SIZE, padded_shapes=([None], [None]))

for input_tensor, output_tensor in ds_series_batch.take(2):
print(input_tensor)
print(output_tensor)
print()

填充将以批处理中输入的最大大小进行。

输出:

tf.Tensor(
[[1 5 3 2]
[2 3 0 0]], shape=(2, 4), dtype=int32)
tf.Tensor(
[[22 5 3 8]
[ 4 7 0 0]], shape=(2, 4), dtype=int32)

tf.Tensor(
[[5 4 8 9 2 1 3]
[1 5 3 2 0 0 0]], shape=(2, 7), dtype=int32)
tf.Tensor(
[[32 4 7 4 5 21 33]
[22 5 3 8 0 0 0]], shape=(2, 7), dtype=int32)

关于python - 使用 TensorFlow Dataset api 导入可变长度的输入/输出对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com