- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我制作了一个 TensorFlow CsvDataset
,我正在尝试将数据标记为这样:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from tensorflow import keras
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
import os
os.chdir('/home/nicolas/Documents/Datasets')
fname = 'rotten_tomatoes_reviews.csv'
def preprocess(target, inputs):
tok = Tokenizer(num_words=5_000, lower=True)
tok.fit_on_texts(inputs)
vectors = tok.texts_to_sequences(inputs)
return vectors, target
dataset = tf.data.experimental.CsvDataset(filenames=fname,
record_defaults=[tf.int32, tf.string],
header=True).map(preprocess)
运行它,出现以下错误:
ValueError: len requires a non-scalar tensor, got one of shape Tensor("Shape:0", shape=(0,), dtype=int32)
我尝试过的:几乎所有可能的领域。请注意,如果我删除预处理步骤,一切都会运行。
数据是什么样的:
(<tf.Tensor: shape=(), dtype=int32, numpy=1>,
<tf.Tensor: shape=(), dtype=string, numpy=b" Some movie critic review...">)
最佳答案
首先,让我们找出代码中的问题:
第一个问题,也是给定错误背后的原因,是 fit_on_texts
方法接受文本列表,而不是单个文本字符串。因此,它应该是:tok.fit_on_texts([inputs])
。
修复该问题并再次运行代码后,您会收到另一个错误:AttributeError: 'Tensor' object has no attribute 'lower'
。这是因为dataset中的元素都是Tensor对象,map函数应该可以处理;然而,Tokenizer
类并不是为处理 Tensor 对象而设计的(这个问题有一个解决方案,但由于下一个问题,我现在不会解决它)。
最大的问题是每次调用 map 函数,即 preprocess
时,都会创建一个 Tokenizer
类的新实例,它会适合在单个文本文档上。 更新:作为@Princy在评论部分正确指出,fit_on_texts
方法实际上执行部分拟合(即更新或扩充内部词汇表统计数据,而不是从头开始)。因此,如果我们在 preprocess
函数之外创建 Tokenizer
类,并且假设词汇集事先已知(否则,您无法过滤最部分拟合方案中的常用词,除非您首先拥有或构建词汇集),那么在应用上述修复后也可以使用这种方法(即基于 Tokenizer
类)。但是,就我个人而言,我更喜欢下面的解决方案。
那么,我们该怎么办呢?如上所述,在几乎所有处理文本数据的模型中,我们首先需要将文本转换为数字特征,即对其进行编码。为了执行编码,首先我们需要一个词汇集或标记字典。因此,我们应该采取的步骤如下:
如果有可用的预建词汇表,则跳至下一步。否则,首先标记化所有文本数据并构建词汇表。
使用词汇集对文本数据进行编码。
为了执行第一步,我们使用 tfds.features.text.Tokenizer
通过迭代数据集来标记文本数据并构建词汇表。
对于第二步,我们使用 tfds.features.text.TokenTextEncoder
使用上一步中构建的词汇集对文本数据进行编码。请注意,对于此步骤,我们使用 map
方法;然而,由于 map
仅在图形模式下起作用,我们将 encode
函数包装在 tf.py_function
中,以便它可以与 map
。
这是代码(请阅读代码中的注释以获取更多要点;我没有将它们包含在答案中,因为它们没有直接关系,但它们很有用且实用):
import tensorflow as tf
import tensorflow_datasets as tfds
from collections import Counter
fname = "rotten_tomatoes_reviews.csv"
dataset = tf.data.experimental.CsvDataset(filenames=fname,
record_defaults=[tf.int32, tf.string],
header=True)
# Create a tokenizer instance to tokenize text data.
tokenizer = tfds.features.text.Tokenizer()
# Find unique tokens in the dataset.
lowercase = True # set this to `False` if case-sensitivity is important.
vocabulary = Counter()
for _, text in dataset:
if lowercase:
text = tf.strings.lower(text)
tokens = tokenizer.tokenize(text.numpy())
vocabulary.update(tokens)
# Select the most common tokens as final vocabulary set.
# Note: if you want all the tokens to be included,
# set `vocab_size = len(vocabulary)` instead.
vocab_size = 5000
vocabulary, _ = zip(*vocabulary.most_common(vocab_size))
# Create an encoder instance given our vocabulary set.
encoder = tfds.features.text.TokenTextEncoder(vocabulary,
lowercase=lowercase,
tokenizer=tokenizer)
# Set this to a non-zero integer if you want the texts
# to be truncated when they have more than `max_len` tokens.
max_len = None
def encode(target, text):
text_encoded = encoder.encode(text.numpy())
if max_len:
text_encoded = text_encoded[:max_len]
return text_encoded, target
# Wrap `encode` function inside `tf.py_function` so that
# it could be used with `map` method.
def encode_pyfn(target, text):
text_encoded, target = tf.py_function(encode,
inp=[target, text],
Tout=(tf.int32, tf.int32))
# (optional) Set the shapes for efficiency.
text_encoded.set_shape([None])
target.set_shape([])
return text_encoded, target
# Apply encoding and then padding.
# Note: if you want the sequences in all the batches
# to have the same length, set `padded_shapes` argument accordingly.
dataset = dataset.map(encode_pyfn).padded_batch(batch_size=3,
padded_shapes=([None,], []))
# Important Note: probably this dataset would be used as input to a model
# which uses an Embedding layer. Therefore, don't forget that you
# should set the vocabulary size for this layer properly, i.e. the
# current value of `vocab_size` does not include the padding (added
# by `padded_batch` method) and also the OOV token (added by encoder).
给 future 读者的旁注:请注意参数的顺序,即 target, text
和数据类型基于 OP 的数据集。根据您自己的数据集/任务根据需要进行调整(尽管在最后,即 return text_encoded, target
,我们对此进行了调整以使其与 fit
方法的预期格式兼容).
关于python - 如何在 map 方法中预处理和标记 TensorFlow CsvDataset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61445913/
我想将模型及其各自训练的权重从 tensorflow.js 转换为标准 tensorflow,但无法弄清楚如何做到这一点,tensorflow.js 的文档对此没有任何说明 我有一个 manifest
我有一个运行良好的 TF 模型,它是用 Python 和 TFlearn 构建的。有没有办法在另一个系统上运行这个模型而不安装 Tensorflow?它已经经过预训练,所以我只需要通过它运行数据。 我
当执行 tensorflow_model_server 二进制文件时,它需要一个模型名称命令行参数,model_name。 如何在训练期间指定模型名称,以便在运行 tensorflow_model_s
我一直在 R 中使用标准包进行生存分析。我知道如何在 TensorFlow 中处理分类问题,例如逻辑回归,但我很难将其映射到生存分析问题。在某种程度上,您有两个输出向量而不是一个输出向量(time_t
Torch7 has a library for generating Gaussian Kernels在一个固定的支持。 Tensorflow 中有什么可比的吗?我看到 these distribu
在Keras中我们可以简单的添加回调,如下所示: self.model.fit(X_train,y_train,callbacks=[Custom_callback]) 回调在doc中定义,但我找不到
我正在寻找一种在 tensorflow 中有条件打印节点的方法,使用下面的示例代码行,其中每 10 个循环计数,它应该在控制台中打印一些东西。但这对我不起作用。谁能建议? 谢谢,哈米德雷萨, epsi
我想使用 tensorflow object detection API 创建我自己的 .tfrecord 文件,并将它们用于训练。该记录将是原始数据集的子集,因此模型将仅检测特定类别。我不明白也无法
我在 TensorFlow 中训练了一个聊天机器人,想保存模型以便使用 TensorFlow.js 将其部署到 Web。我有以下内容 checkpoint = "./chatbot_weights.c
我最近开始学习 Tensorflow,特别是我想使用卷积神经网络进行图像分类。我一直在看官方仓库中的android demo,特别是这个例子:https://github.com/tensorflow
我目前正在研究单图像超分辨率,并且我设法卡住了现有的检查点文件并将其转换为 tensorflow lite。但是,使用 .tflite 文件执行推理时,对一张图像进行上采样所需的时间至少是使用 .ck
我注意到 tensorflow 的 api 中已经有批量标准化函数。我不明白的一件事是如何更改训练和测试之间的程序? 批量归一化在测试和训练期间的作用不同。具体来说,在训练期间使用固定的均值和方差。
我创建了一个模型,该模型将 Mobilenet V2 应用于 Google colab 中的卷积基础层。然后我使用这个命令转换它: path_to_h5 = working_dir + '/Tenso
代码取自:- http://adventuresinmachinelearning.com/python-tensorflow-tutorial/ import tensorflow as tf fr
好了,所以我准备在Tensorflow中运行 tf.nn.softmax_cross_entropy_with_logits() 函数。 据我了解,“logit”应该是概率的张量,每个对应于某个像素的
tensorflow 服务构建依赖于大型 tensorflow ;但我已经成功构建了 tensorflow。所以我想用它。我做这些事情:我更改了 tensorflow 服务 WORKSPACE(org
Tensoflow 嵌入层 ( https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding ) 易于使用, 并且有大量的文
我正在尝试使用非常大的数据集(比我的内存大得多)训练 Tensorflow 模型。 为了充分利用所有可用的训练数据,我正在考虑将它们分成几个小的“分片”,并一次在一个分片上进行训练。 经过一番研究,我
根据 Sutton 的书 - Reinforcement Learning: An Introduction,网络权重的更新方程为: 其中 et 是资格轨迹。 这类似于带有额外 et 的梯度下降更新。
如何根据条件选择执行图表的一部分? 我的网络有一部分只有在 feed_dict 中提供占位符值时才会执行.如果未提供该值,则采用备用路径。我该如何使用 tensorflow 来实现它? 以下是我的代码
我是一名优秀的程序员,十分优秀!