gpt4 book ai didi

python - 使用 Tensorflow 处理文本数据 2 "ERROR: Attempted to pad to a smaller size than the input element"

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

我在遍历标记化文本数据集时遇到此错误:

tensorflow.python.framework.errors_impl.DataLossError: Attempted to pad to a smaller size than the input element

这可能是因为我根本无法理解 padded_shapes=([None], (1,)) 参数。这是 dataset和代码:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow_datasets as tfds
from collections import Counter

os.chdir('/home/nicolas/Documents/Datasets')

data = tf.data.experimental.CsvDataset('rotten_tomatoes_string.csv',
record_defaults=[tf.string, tf.string],
header=True, select_cols=[0, 1])

review_tokenizer= tfds.features.text.Tokenizer()
vocabulary = Counter()

for ix, (_, review) in enumerate(data):
review = tf.strings.lower(review)
tokens = review_tokenizer.tokenize(review.numpy())
vocabulary.update(tokens)

vocabulary = [key for (key, value) in vocabulary.items() if value >= 5 and len(key) > 2]

ratings = {'rotten', 'fresh'}
review_encoder = tfds.features.text.TokenTextEncoder(vocabulary)
freshness_encoder = tfds.features.text.TokenTextEncoder(ratings)

def encode(freshness, review):
review = review_encoder.encode(review.numpy())
freshness = freshness_encoder.encode(freshness.numpy())
return freshness, review

def tf_map(freshness, review):
encoded_freshness, review = tf.py_function(encode,
inp=[freshness, review],
Tout=[tf.int32, tf.int32])
review.set_shape([None])
encoded_freshness.set_shape(1,)
return encoded_freshness, review


TAKE = 480_000

train_data = data.map(tf_map).take(1000)
train_data = train_data.padded_batch(8, padded_shapes=([None], (1,)))

next(iter(train_data))

我该如何处理?

最佳答案

使用 padded_shapes=([None], (1,)) 您请求将第二个元素填充到 1 的大小。但是,您应该考虑:

  1. 第二个元素是评论标记(查看 tf_map 函数的 return 语句),它可能包含数十或数百个值(对于每个示例)。

  2. Datasetpadded_batch 方法不做任何截断;它只能做填充。

因此,根据以上两点,你会得到问题中提到的错误。相反,使用更高的constant 维度大小(它应该大于数据集中所有样本的长度;否则你会得到同样的错误),或者使用[None] 将每批填充到适合的最小尺寸(即每批中样本的最大长度)。

关于python - 使用 Tensorflow 处理文本数据 2 "ERROR: Attempted to pad to a smaller size than the input element",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61720555/

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