gpt4 book ai didi

python - 将形状不等的数组列表转换为 Tensorflow 2 数据集 : ValueError: Can't convert non-rectangular Python sequence to Tensor

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

我以形状不均数组列表的形式对数据进行了标记化:

array([array([1179,    6,  208,    2, 1625,   92,    9, 3870,    3, 2136,  435,
5, 2453, 2180, 44, 1, 226, 166, 3, 4409, 49, 6728,
...
10, 17, 1396, 106, 8002, 7968, 111, 33, 1130, 60, 181,
7988, 7974, 7970])], dtype=object)

各自的目标:

Out[74]: array([0, 0, 0, ..., 0, 0, 1], dtype=object)

我正在尝试将它们转换为填充的 tf.data.Dataset(),但它不允许我将不相等的形状转换为张量。我会得到这个错误:

ValueError: Can't convert non-rectangular Python sequence to Tensor.

完整代码在这里。假设我的起点是在 y = ... 之后:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np

(train_data, test_data) = tfds.load('imdb_reviews/subwords8k',
split=(tfds.Split.TRAIN, tfds.Split.TEST),
as_supervised=True)

x = np.array(list(train_data.as_numpy_iterator()))[:, 0]
y = np.array(list(train_data.as_numpy_iterator()))[:, 1]


train_tensor = tf.data.Dataset.from_tensor_slices((x.tolist(), y))\
.padded_batch(batch_size=8, padded_shapes=([None], ()))

将其转换为填充批处理张量有哪些选择?

最佳答案

如果您的数据存储在 Numpy 数组或 Python 列表中,那么您可以使用 tf.data.Dataset.from_generator创建数据集然后填充批处理的方法:

train_batches = tf.data.Dataset.from_generator(
lambda: iter(zip(x, y)),
output_types=(tf.int64, tf.int64)
).padded_batch(
batch_size=32,
padded_shapes=([None], ())
)

但是,如果您使用的是tensorflow_datasets.load函数,那么就没有必要使用as_numpy_iterator来分离数据和标签,然后再将它们组合在一起在数据集中!这是多余且低效的。 tensorflow_datasets.load 返回的对象已经是 tf.data.Dataset 的实例。因此,您只需要对它们使用 padded_batch:

train_batches = train_data.padded_batch(batch_size=32, padded_shapes=([None], []))
test_batches = test_data.padded_batch(batch_size=32, padded_shapes=([None], []))

请注意,在 TensorFlow 2.2 及更高版本中,如果您只想将所有轴填充到批处理中的最长轴(即默认行为),则不再需要提供 padded_shapes 参数。

关于python - 将形状不等的数组列表转换为 Tensorflow 2 数据集 : ValueError: Can't convert non-rectangular Python sequence to Tensor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61334069/

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