Keras TextVectorization指定词汇表时大小写敏感问题及用法咨询
正确使用Keras TextVectorization的vocabulary参数
问题的核心在于TextVectorization默认的文本标准化行为与手动指定词汇表的格式不匹配:
- 默认
standardize='lower_and_strip_punctuation'会将输入文本全部转为小写; - 手动传入
vocabulary时,词汇表的大小写会被严格保留,导致输入的小写变体(如b)无法匹配词汇表中的大写条目(如B),被归类为[UNK]; - 使用
adapt时,构建词汇表的过程会遵循标准化规则,自动将训练词汇转小写,因此输入的大小写变体能正常匹配。
以下是三种针对性解决方案:
方案一:统一词汇表为小写(保持默认标准化)
将手动指定的词汇表转为小写,确保输入文本转小写后能匹配词汇表:
import keras v = { "deck": ['a','B','C','D','E','F','G','H','I','J','K','L'] } # 词汇表统一转小写 lower_deck = [word.lower() for word in v["deck"]] print(len(lower_deck)) l = keras.layers.TextVectorization( max_tokens=len(lower_deck)+2, vocabulary=lower_deck, output_mode='count', name="deck" ) print(l.vocabulary_size()) print(l.get_vocabulary()) print(l('a A b B'))
输出示例:
12 13 ['[UNK]', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] tf.Tensor([0. 2. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.], shape=(13,), dtype=float32)
方案二:关闭自动转小写(严格匹配大小写)
如果需要保留词汇表的大小写,仅统计与词汇表完全一致的输入,修改standardize参数为'strip_punctuation'(仅去除标点,不转小写):
import keras v = { "deck": ['a','B','C','D','E','F','G','H','I','J','K','L'] } print(len(v["deck"])) l = keras.layers.TextVectorization( max_tokens=len(v["deck"])+2, vocabulary=v["deck"], output_mode='count', name="deck", standardize='strip_punctuation' # 关闭自动转小写 ) print(l.vocabulary_size()) print(l.get_vocabulary()) print(l('a A b B'))
输出示例:
12 13 ['[UNK]', 'a', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'] tf.Tensor([2. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.], shape=(13,), dtype=float32)
此时只有a和B会被统计,A和b因大小写不匹配被归为[UNK]。
方案三:自定义标准化函数(灵活匹配大小写)
如果需要实现自定义的大小写映射逻辑(比如输入转大写匹配词汇表),可以自定义standardize函数:
import keras import tensorflow as tf def custom_standardize(input_string): # 去除标点后将文本转大写 stripped = tf.strings.regex_replace(input_string, '[^\w\s]', '') return tf.strings.upper(stripped) v = { "deck": ['a','B','C','D','E','F','G','H','I','J','K','L'] } # 词汇表统一转大写,匹配自定义标准化后的输入 upper_deck = [word.upper() for word in v["deck"]] print(len(upper_deck)) l = keras.layers.TextVectorization( max_tokens=len(upper_deck)+2, vocabulary=upper_deck, output_mode='count', name="deck", standardize=custom_standardize ) print(l.vocabulary_size()) print(l.get_vocabulary()) print(l('a A b B'))
输出示例:
12 13 ['[UNK]', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'] tf.Tensor([0. 2. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.], shape=(13,), dtype=float32)
核心要点
- 手动指定
vocabulary时,必须确保词汇表的格式与standardize处理后的输入格式一致; - 默认标准化规则会转小写,是导致大小写不匹配的主要原因;
- 根据业务需求选择合适的标准化策略,或自定义函数实现灵活匹配。
内容的提问来源于stack exchange,提问作者PGT
相关产品推荐
相关产品推荐

