"""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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-text-data-processing-lab/transform-and-classify-text.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
transform-and-classify-text.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a382.zip