蓝色天空网mbsky.com · 知识 · 实践 · 创造TensorFlow · 本地阅读预览
教程 / AI / 智能开发 / TensorFlow

TensorFlow 文本数据处理

用可核对的 UTF-8 字符串、词表和两种分类输入练习文本预处理。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先说明文本的输入约定

建模前先约定编码、字词边界和保留信息。大小写、标点、停用词、特殊字符和拼写变体的处理要随任务调整。例如情感分类应谨慎处理否定词,拼写近似也可能碰到人名和产品名。保存原始输入,方便对照清洗前后的含义。

TensorFlow 核心库可以用 tf.strings 处理字符串,用 TextLineDataset 逐行读 UTF-8 文件,再用 Keras TextVectorization 将文本转成数值张量。TensorFlow Text 是可选扩展,按 Python、操作系统和 TensorFlow 版本核对安装文件。

逐项检查大小写、分隔和字符数

对 ÉCOLE 夏! 使用默认 lower 仅改变 ASCII 大写;指定 UTF-8 后 É 也会变为 é。tf.strings.split 默认按空白分割,连写的中文保留为一个单元。汉A 是 4 个 UTF-8 字节、2 个 Unicode 码点;tf.strings.length 默认数 bytes,使用 UTF8_CHAR 数码点。组合重音和连字表情仍可能由多个码点组成。

ASCII 标点删除会把 Good-night 连接成 Goodnight,且保留中文顿号。使用 RE2 的 Unicode 字符类别保留字母、数字和组合标记,其余字符折成空格,可以清楚观察中文顿号和表情的处理结果。清洗策略依任务而定,符号在部分任务中也有预测价值。

让词表与输入形式对应

训练词表时,把一批或一维文本交给 adapt;也可在部署时显式提供固定词表。使用固定词表晴天、雨天时,整数模式为所给词依次分配 2、3,0 是掩码或补齐,1 是词表外索引。给 output_sequence_length 指定 4,可实测短句补齐和长句截断。get_vocabulary 会返回保留项及词表顺序。

整数、出现标记、计数和 TF-IDF 的向量含义各有区别。以同一句中的两次晴天为例,多热列仍是 1,计数列是 2。TF-IDF 用词频乘权重,权重可以提供或由训练文档适配。当前版本仍接受 binary 和 tf-idf,配置和新代码采用 multi_hot 与 tf_idf。

区分按空白切分与子词分词

TensorFlow Text 的 WhitespaceTokenizer 适用于已有空白边界的文本。示例可以输入两行词间含空格的文本并观察变长结果。连写中文需要匹配任务的分词或子词策略。当前 Windows 环境已用核心库验证空白边界,选装分词器仍待在匹配发行包的环境运行。

BertTokenizer 先做基础切分,再按词表做 WordPiece 匹配。词表文件或查找表必须与模型配套;通常用 ## 表示词中后缀,用 [UNK] 表示词表外。输出 token_out_type 可设 tf.int64 取编号,或 tf.string 观察片段。预处理模型输入时还需按模型规则处理起止标记、掩码与所需长度。

把清洗与训练组织成两条可运行路径

本地练习逐行清洗,再将有限、确定的结果缓存,按两行一批向量化并预取。缓存需要完整消费后才能重用。超出内存时可用文件缓存、流式生成器或带版本的离线预处理。性能设置需要评估实际输入、输出顺序和内存。

本站合成短评实验只用训练文本适配词表,模型依次执行向量化、嵌入、掩码平均池化和二分类。留出的未知词映射到 1。Keras IMDb 读取器交付的是已编码的整数序列,对变长整数做 pad_sequences 后直接送给 Embedding;要做字符串适配,应从原始评论文本开始。这两种输入契约都以本站合成数据运行。

核对补齐、词表边界和一致性

依据训练文本的词频、长度分布与内存预算选择词表上限和序列长度,记录截断比例。pad_to_max_tokens 固定的是多热、计数或 TF-IDF 的特征宽度;整数序列靠 output_sequence_length。训练、验证和推理共享词表、字符处理和填充值,多语言文本按各自的词边界确定切分。

向量化模式对照

当前模式输出适用场景
int按词序输出整数索引,可补齐或截断。作为 Embedding 输入。
multi_hot每词一列,出现一次或多次都为 1;binary 是旧别名。短文本分类的出现标记。
count每列累加对应词或词表外标记出现的次数。保留频次的词袋特征。
tf_idf词频乘对应逆文档权重;tf-idf 是旧别名。文本相关度或检索特征。

观察文本的四种编码并训练一个小型分类器

python · 阅读源码
"""Verify UTF-8 text, vectorization modes and two input paths for classification."""
import json
import platform
import string
from pathlib import Path
from tempfile import TemporaryDirectory

import numpy as np
import tensorflow as tf
from tensorflow import keras


def observe(cases, name, operation, inputs, expected, actual, measurements=None):
    assert actual == expected, (name, expected, actual)
    row = dict(name=name, operation=operation, inputs=inputs,
               expected=expected, actual=actual, passed=True)
    if measurements is not None:
        row["measurements"] = measurements
    cases.append(row)


def decode(values):
    return [item.decode("utf-8") for item in values]


def clean_text(text):
    lowered = tf.strings.lower(text, encoding="utf-8")
    return tf.strings.strip(tf.strings.regex_replace(lowered, r"[^\p{L}\p{N}\p{M}]+", " "))


def options_for_local_run(dataset):
    dataset_options = tf.data.Options()
    dataset_options.threading.private_threadpool_size = 1
    return dataset.with_options(dataset_options)


def main():
    cases = []
    keras.utils.set_random_seed(734)
    phrases = ["ÉCOLE 夏!", "深度学习自然语言处理", "文🙂"]
    text = tf.constant(phrases)
    observe(cases, "unicode_lower", "Compare default and UTF-8 lowercasing",
            phrases[:1], [["École 夏!"], ["école 夏!"]],
            [decode(tf.strings.lower(text[:1]).numpy()),
             decode(tf.strings.lower(text[:1], encoding="utf-8").numpy())])
    observe(cases, "utf8_lengths", "Compare UTF-8 bytes with code points",
            ["汉A", *phrases[1:]], [[4, 30, 7], [2, 10, 2]],
            [tf.strings.length(["汉A", *phrases[1:]]).numpy().tolist(),
             tf.strings.length(["汉A", *phrases[1:]], unit="UTF8_CHAR").numpy().tolist()])
    spaced = ["深度学习自然语言处理", "深度学习 自然语言处理"]
    observe(cases, "whitespace_boundary", "Split two strings with the same visible words and different spacing",
            spaced, [[spaced[0]], ["深度学习", "自然语言处理"]],
            [decode(row) for row in tf.strings.split(spaced).to_list()])

    source_text = ["Good-night!", "天气、晴朗。", "ÉTÉ🙂"]
    punctuation_class = "[" + string.punctuation.translate(str.maketrans({
        char: "\\" + char for char in "\\]-^"
    })) + "]"
    removed = tf.strings.regex_replace(source_text[:2], punctuation_class, "")
    observe(cases, "regex_cleanup", "Compare deleting ASCII punctuation with replacing Unicode separators",
            source_text, [["Goodnight", "天气、晴朗。"], ["good night", "天气 晴朗", "été"]],
            [decode(removed.numpy()), decode(clean_text(source_text).numpy())])

    with TemporaryDirectory() as directory:
        corpus_path = Path(directory) / "short-notes.txt"
        corpus_path.write_bytes("清晨 散步\n夜晚 读书\n".encode("utf-8"))
        file_data = options_for_local_run(tf.data.TextLineDataset(str(corpus_path)))
        observe(cases, "utf8_lines", "Write private synthetic UTF-8 data and read two lines as strings",
                {"lines": 2, "separator": "LF"}, ["清晨 散步", "夜晚 读书"],
                decode(file_data.as_numpy_iterator()))

    vocabulary = ["晴天", "雨天"]
    sample = ["晴天 晴天 雨天 陌生词", "雨天"]
    integer = keras.layers.TextVectorization(vocabulary=vocabulary, output_sequence_length=4)
    observe(cases, "integer_indices", "Use the vocabulary order, retain repeated tokens, pad and truncate to four",
            sample, [["", "[UNK]", *vocabulary], [[2, 2, 3, 1], [3, 0, 0, 0]], [[2, 2, 2, 2]]],
            [integer.get_vocabulary(), integer(sample).numpy().tolist(),
             integer(["晴天 晴天 晴天 晴天 雨天"]).numpy().tolist()])

    features = {}
    for mode, name, expected in [
        ("multi_hot", "multi_hot_presence", [[1., 1., 1.], [0., 0., 1.]]),
        ("count", "token_count", [[1., 2., 1.], [0., 0., 1.]]),
        ("tf_idf", "tf_idf_weights", [[1.5, 4., 1.], [0., 0., 1.]]),
    ]:
        settings = {"idf_weights": [2., 1.]} if mode == "tf_idf" else {}
        layer = keras.layers.TextVectorization(vocabulary=vocabulary, output_mode=mode, **settings)
        features[mode] = layer(sample).numpy().tolist()
        observe(cases, name, "Compare the OOV, 晴天 and 雨天 feature columns",
                {"sentences": sample, "mode": mode, **settings}, expected, features[mode])
    aliases = {}
    for old_name, canonical in [("binary", "multi_hot"), ("tf-idf", "tf_idf")]:
        settings = {"idf_weights": [2., 1.]} if canonical == "tf_idf" else {}
        old_layer = keras.layers.TextVectorization(vocabulary=vocabulary, output_mode=old_name, **settings)
        aliases[old_name] = [old_layer.get_config()["output_mode"],
                             old_layer(sample).numpy().tolist() == features[canonical]]
    observe(cases, "legacy_mode_aliases", "Check the canonical settings and numeric equality",
            ["binary", "tf-idf"], {"binary": ["multi_hot", True], "tf-idf": ["tf_idf", True]}, aliases)

    int_fixed = keras.layers.TextVectorization(vocabulary=vocabulary, max_tokens=6,
        output_mode="int", output_sequence_length=4, pad_to_max_tokens=True)
    multi_fixed = keras.layers.TextVectorization(vocabulary=vocabulary, max_tokens=6,
        output_mode="multi_hot", pad_to_max_tokens=True)
    observe(cases, "oov_and_padding", "Compare unknown token, zero padding, and max-token feature width",
            {"sample": "晴天 未见词", "max_tokens": 6, "sequence_length": 4},
            [[[2, 1, 0, 0]], [[1., 1., 0., 0., 0., 0.]]],
            [int_fixed(["晴天 未见词"]).numpy().tolist(), multi_fixed(["晴天 未见词"]).numpy().tolist()])

    cleaned = options_for_local_run(tf.data.Dataset.from_tensor_slices(
        ["晴天、雨天", "雨天?", "陌生词🙂"]).map(clean_text))
    packed = cleaned.cache().batch(2).map(integer).prefetch(1)
    expected_batches = [[[2, 3, 0, 0], [3, 0, 0, 0]], [[1, 0, 0, 0]]]
    observe(cases, "batched_text_pipeline", "Map Unicode cleaning, cache, batch, vectorize and prefetch twice",
            {"lines": 3, "batch_size": 2}, [expected_batches, expected_batches],
            [[batch.tolist() for batch in packed.as_numpy_iterator()] for _ in range(2)])

    training_text = ["bright tender", "delightful bright", "tender delightful", "bright warm",
                     "dull flat", "bleak dull", "flat bleak", "dull cold"]
    training_labels = [1, 1, 1, 1, 0, 0, 0, 0]
    evaluation_text = ["bright tender encore", "dull bleak review"]
    evaluation_labels = [1, 0]
    train_tokens = options_for_local_run(tf.data.Dataset.from_tensor_slices(training_text).batch(4))
    classifier_vectorizer = keras.layers.TextVectorization(max_tokens=16, output_sequence_length=5)
    classifier_vectorizer.adapt(train_tokens)
    classifier = keras.Sequential([
        keras.Input(shape=(), dtype=tf.string), classifier_vectorizer,
        keras.layers.Embedding(16, 8, mask_zero=True), keras.layers.GlobalAveragePooling1D(),
        keras.layers.Dense(1, activation="sigmoid"),
    ])
    classifier.compile(optimizer=keras.optimizers.Adam(0.05),
                       loss="binary_crossentropy", metrics=["accuracy"])
    train = options_for_local_run(tf.data.Dataset.from_tensor_slices(
        (training_text, training_labels)).batch(4))
    history = classifier.fit(train, epochs=15, verbose=0)
    evaluation_ids = classifier_vectorizer(evaluation_text).numpy()
    probabilities = classifier(tf.constant(evaluation_text), training=False).numpy().ravel()
    observe(cases, "raw_sentiment_training", "Adapt only to train texts, train a binary model and classify holdout texts",
            {"train": list(zip(training_text, training_labels)), "test": list(zip(evaluation_text, evaluation_labels)),
             "epochs": 15, "batch_size": 4}, [30, True, [1, 0], [1, 1], True],
            [int(classifier.optimizer.iterations), bool(history.history["loss"][-1] < history.history["loss"][0]),
             (probabilities >= 0.5).astype(int).tolist(), evaluation_ids[:, 2].tolist(),
             bool(np.all(evaluation_ids[:, 3:] == 0))],
            {"first_loss": float(history.history["loss"][0]), "final_loss": float(history.history["loss"][-1]),
             "test_probabilities": probabilities.tolist(), "test_token_ids": evaluation_ids.tolist()})

    already_encoded = [[1, 7, 2], [1, 5, 3, 4, 6]]
    padded = keras.utils.pad_sequences(already_encoded, maxlen=4, padding="post", truncating="post")
    integer_model = keras.Sequential([keras.Input(shape=(4,), dtype=tf.int32),
        keras.layers.Embedding(10, 4, mask_zero=True), keras.layers.GlobalAveragePooling1D(),
        keras.layers.Dense(1, activation="sigmoid")])
    integer_model.compile(optimizer="adam", loss="binary_crossentropy")
    training_loss = float(integer_model.train_on_batch(padded, tf.constant([1, 0])))
    predictions = integer_model(padded).numpy()
    observe(cases, "preencoded_sentiment_input", "Pad synthetic integer sequences and pass them directly to an embedding",
            {"ids": already_encoded, "labels": [1, 0]}, [[[1, 7, 2, 0], [1, 5, 3, 4]], [2, 1], 1, True],
            [padded.tolist(), list(predictions.shape), int(integer_model.optimizer.iterations),
             bool(np.isfinite(predictions).all() and np.isfinite(training_loss))],
            {"batch_loss": training_loss, "probabilities": predictions[:, 0].tolist()})

    print(json.dumps(dict(version=platform.python_version(), tensorflow=tf.__version__,
        keras=keras.__version__, system=platform.system(),
        devices=[device.name for device in tf.config.list_physical_devices()], cases=cases)))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 查看重复词的出现标记、计数和权重,以及训练词表外的词如何进入两种分类管道。
观察文本的四种编码并训练一个小型分类器

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

当前源码 SHA256:b380cb47f125f00ea955a5b3b4e0f303497381d6fc4b832b97b7b491e2e84b27

下载本站示例源码

本地运行

解压后按 README 运行本站程序。

下载TensorFlow 文本数据处理实例

所需环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。

ZIP SHA256:e86068a65b21a993bec79dd4621e47efe5c2409fafc26a092e49fba456b1134d

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

已得到 IMDb 整数序列时,下一步送入哪个处理环节?

展开参考解答

先按模型长度补齐或截断,然后直接送给嵌入层。

规范与官方依据