如何使用 TensorFlow Tokenizer 的 texts_to_sequences?
texts_to_sequences() 可以用于这个程序。先用 fit_on_texts() 建立词表,再将文本转换成整数序列。训练时,Embedding 接收词索引,sparse_categorical_crossentropy 接收下一个词的整数索引作为标签。
临时方案中的 [i, words] 将标题编号和整句文本放在一起,导致训练标签中出现字符串。Invalid dtype: str480 就表示模型处理到了 NumPy 字符串类型的数据。
正确调用 texts_to_sequences()
清洗文本后,按以下顺序调用:
self.tokenizer.fit_on_texts(preprocessed_titles)
self.sequences = self.tokenizer.texts_to_sequences(preprocessed_titles)
self.vocab_size = len(self.tokenizer.word_index) + 1
例如:
from tensorflow.keras.preprocessing.text import Tokenizer
texts = ["deep learning works", "deep learning"]
tokenizer = Tokenizer()
tokenizer.fit_on_texts(texts)
print(tokenizer.word_index)
# {'deep': 1, 'learning': 2, 'works': 3}
print(tokenizer.texts_to_sequences(texts))
# [[1, 2, 3], [1, 2]]
返回结果是一个包含多个整数列表的列表,每个序列的长度可以不同。送入模型前,再用 pad_sequences() 补齐。
原代码中,转换调用被注释掉了,因此这一行只创建了空列表:
self.sequences = [] # tokenizer.texts_to_sequences(preprocessed_titles)
在类的方法中,应通过 self.tokenizer 访问已经建立词表的实例。
两个错误分别意味着什么?
invalid literal for int() with base 10
这个错误表示程序尝试将一个无法解析为整数的字符串转换成整数。
报错片段:
trunc = np.asarray(trunc, dtype=dtype)
这通常发生在 pad_sequences() 将序列转换成整数数组时。如果传入的仍是单词或句子,转换就可能失败。具体在哪次调用中出错,需要查看完整堆栈。
文本需要先通过词表转换成词索引:
["deep", "learning"] # 单词
[1, 2] # 对应的词索引
仅设置 dtype="int32" 无法完成这种映射。
Invalid dtype: str480
str480 是 NumPy 定长 Unicode 字符串类型的一种名称。其中的数字表示字符串的存储宽度,与词表大小、模型输入维度无关。在 NumPy 常见的定长 Unicode 表示中,每个字符位置占 32 位,str480 对应 15 个字符位置。
问题出在这段代码:
for i, words in enumerate(preprocessed_titles):
self.sequences.append([i, words])
假设得到:
self.sequences = [
[0, "deep learning"],
[1, "neural networks"]
]
原来的样本构造循环会产生:
self.input_sequences = [[0], [1]]
self.output_sequences = ["deep learning", "neural networks"]
接着执行:
self.output_sequences = np.array(self.output_sequences)
得到的就是字符串数组。当前模型的损失函数需要整数类别标签,无法将这些句子用作标签,因此可能报出 Invalid dtype: str480。类型名称中的数字会随字符串长度变化。
训练样本应从词索引序列中构造。例如,序列 [4, 7, 9] 可以产生:
| 输入前缀 | 目标词索引 |
|---|---|
[4] |
7 |
[4, 7] |
9 |
修正训练和生成流程
下面沿用问题中的 preprocess_text(),假设它已正确定义,且 JSON 的 "A" 字段是字符串列表。训练和生成分别调用,生成时传入种子文本。
import json
import numpy as np
from tensorflow.keras import Input, Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
class GenTitle:
def __init__(self, json_path):
self.json_path = json_path
self.tokenizer = None
self.model = None
self.maxlen = None
def fit(self, epochs=50, batch_size=128):
with open(self.json_path, "r", encoding="utf-8") as file:
content = json.load(file)
titles = [
preprocess_text(title)
for title in content["A"]
]
self.tokenizer = Tokenizer()
self.tokenizer.fit_on_texts(titles)
sequences = self.tokenizer.texts_to_sequences(titles)
vocab_size = len(self.tokenizer.word_index) + 1
inputs = []
targets = []
for seq in sequences:
for i in range(1, len(seq)):
inputs.append(seq[:i])
targets.append(seq[i])
if not inputs:
raise ValueError("清洗后至少需要一个包含两个有效词的标题。")
self.maxlen = max(len(seq) for seq in inputs)
x = pad_sequences(
inputs,
maxlen=self.maxlen,
padding="post",
truncating="pre",
dtype="int32",
)
y = np.asarray(targets, dtype="int32")
self.model = Sequential([
Input(shape=(self.maxlen,), dtype="int32"),
Embedding(
input_dim=vocab_size,
output_dim=50,
mask_zero=True,
),
LSTM(100),
Dense(vocab_size, activation="softmax"),
])
self.model.compile(
loss="sparse_categorical_crossentropy",
optimizer=Adam(learning_rate=0.01),
)
self.model.fit(
x,
y,
epochs=epochs,
batch_size=batch_size,
)
def generate_title(self, seed_text, max_new_tokens=10):
if self.model is None:
raise RuntimeError("请先调用 fit() 训练模型。")
cleaned_seed = preprocess_text(seed_text)
token_ids = self.tokenizer.texts_to_sequences(
[cleaned_seed]
)[0]
if not token_ids:
raise ValueError("种子文本清洗后没有词表中已收录的词。")
generated_words = []
for _ in range(max_new_tokens):
encoded_text = pad_sequences(
[token_ids],
maxlen=self.maxlen,
padding="post",
truncating="pre",
dtype="int32",
)
probabilities = self.model.predict(
encoded_text,
verbose=0,
)[0]
# 0 用于补齐,生成时排除它。
probabilities[0] = 0.0
next_id = int(np.argmax(probabilities))
generated_words.append(
self.tokenizer.index_word[next_id]
)
token_ids.append(next_id)
return " ".join(generated_words)
generator = GenTitle("dataSheets/trainingData.JSON")
generator.fit()
# 示例种子应替换为训练语料中出现过的词。
print(generator.generate_title("deep learning", max_new_tokens=10))
x 的形状是 (样本数, 最大前缀长度),y 的形状是 (样本数,),两者都是整数数组。计算 vocab_size 时加一,是因为索引 0 留给补齐位置。
生成方法只返回新预测的词,不包含原始种子文本。
原程序中还需要修正的地方
read_JsonFile() 没有 return,因此执行:
seed_text = self.read_JsonFile()
后,seed_text 的值是 None。函数上的 -> str 类型注解不会自动产生返回值。可以让读取函数返回一个明确的字符串,也可以像示例一样,在生成时单独传入种子文本。
texts_to_sequences([seed_text]) 返回的已经是一批序列:
encoded_text = self.tokenizer.texts_to_sequences([seed_text])
# 形如 [[1, 2, 3]]
直接传给 pad_sequences() 即可:
encoded_text = pad_sequences(
encoded_text,
maxlen=self.input_sequences.shape[1],
)
原来的 pad_sequences([encoded_text], ...) 在外面多包了一层列表,会引入额外维度。
预测后,应先取出单个整数索引,再查反向词表:
probabilities = self.model.predict(encoded_text, verbose=0)
predicted_word_index = int(np.argmax(probabilities[0]))
predicted_word = self.tokenizer.index_word.get(predicted_word_index)
无法使用 Tokenizer 时有哪些替代方法?
如果文本已经清洗完毕,并用空格分隔,可以自己建立词表:
word_index = {}
for text in preprocessed_titles:
for word in text.split():
if word not in word_index:
word_index[word] = len(word_index) + 1
sequences = [
[word_index[word] for word in text.split()]
for text in preprocessed_titles
]
vocab_size = len(word_index) + 1
这段代码按词首次出现的顺序分配索引,分词和排序规则与 Tokenizer 的默认行为并不完全相同。训练和生成必须使用同一个词表,并明确如何处理未知词。
也可以使用 tensorflow.keras.layers.TextVectorization,通过 adapt() 建立词表,设置 output_mode="int" 后输出整数序列。更换编码方式时,反向词表、未知词处理和补齐逻辑也需要同步调整。
文本清洗与标题质量的注意事项
默认的 Tokenizer() 会跳过词表中没有的词,因此种子文本可能被编码成空列表。示例中已检查这种情况,训练和生成时也应保持清洗规则一致。
原来的 preprocess_text() 会删除停用词,并使用 PorterStemmer 提取词干。模型学到的是处理后的词,生成结果可能缺少冠词、介词,或出现词干形式。要生成自然、完整的标题,通常应保留这些语言信息。
清洗函数中的 except Exception 捕获范围过宽,可能掩盖 NLTK 资源缺失等问题,导致部分文本采用另一套清洗规则。排查时应保留异常信息,并显式导入所需模块,例如 string 和 stopwords。
这套模型根据已有词预测下一个词。由于没有接收文章正文,仅凭这段训练流程无法生成与某篇文章内容对应的标题。示例中也没有结束标记,生成长度由 max_new_tokens 控制。
备注:内容仅供参考。
