问题
将调整后的TextVectorization应用于文本数据集时,请帮助理解错误的原因。
背景
Keras for Engineers简介中有一部分将自适应的TextVectorization层应用于文本数据集。
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
training_data = np.array([["This is the 1st sample."], ["And here's the 2nd sample."]])
vectorizer = TextVectorization(output_mode="int")
vectorizer.adapt(training_data)
integer_data = vectorizer(training_data) # <----- Apply the adapted TextVectorization
问题
尝试同样的方法,首先将TextVectorization层应用于PTB文本,然后将其应用于莎士比亚文本。
将文本矢量化应用于PTB
f = "ptb.train.txt"
path_to_ptb = tf.keras.utils.get_file(
str(pathlib.Path().absolute()) + '/' + f,
f'https://raw.githubusercontent.com/tomsercu/lstm/master/data/{f}'
)
ptb_ds = tf.data.TextLineDataset(
filenames=path_to_file, compression_type=None, buffer_size=None, num_parallel_reads=True
)
.filter(lambda x: tf.cast(tf.strings.length(x), bool))
.shuffle(10000)
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
vectorizer = TextVectorization(output_mode="int", ngrams=None)
vectorizer.adapt(ptb_ds)
将TextVectorization层应用于莎士比亚的文本,结果出现错误
path_to_shakespeare = tf.keras.utils.get_file(
'shakespeare.txt',
'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt'
)
shakespeare_ds = tf.data.TextLineDataset(path_to_shakespeare)
.filter(lambda x: tf.cast(tf.strings.length(x), bool))
shakespeare_vector_ds =
vectorizer(shakespeare_ds.batch(128).prefetch(tf.data.AUTOTUNE)) <----- Error
错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-48-216442e69438> in <module>
----> 1 shakespeare_vector_ds = vectorizer(shakespeare_ds.batch(128).prefetch(tf.data.AUTOTUNE))
...
alueError: Attempt to convert a value (<PrefetchDataset shapes: (None,), types: tf.string>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.PrefetchDataset'>) to a Tensor.
解决方案
这是有效的,但不清楚上面为什么会导致错误,尽管它似乎也在做同样的事情。
- Tensorflow Word2Verc教程
shakespeare_vector_ds =
shakespeare_ds.batch(1024).prefetch(tf.data.AUTOTUNE).map(vectorizer).unbatch()
tf.data.Dataset.map
将一个函数应用于数据集的每个元素(张量(。TextVectorization
对象的__call__
方法需要Tensor
,而不是tf.data.Dataset
对象。每当您想将函数应用于tf.data.Dataset
的元素时,都应该使用map
。