TensorFlow 2如何将字符串张量转换为词袋表示?符合图模式要求的实现求助
需求:TensorFlow图模式下实现字符串张量转词袋稀疏张量
我需要编写一个函数,接收字符串张量作为输入,返回由0和1组成的稀疏张量,每一行对应输入中一个字符串的词袋表示。
输入说明
- 每个输入字符串是由1~7个单词组成的名称
- 单个名称中每个单词仅会出现0次或1次
- 输入已全部转为小写,仅包含字母和数字
- 输入张量中同一个名称可能多次出现
- 不同名称之间存在重复出现的单词
实现要求
- 函数需携带
k_top参数,指定纳入统计的最高频单词数量(即词汇表大小) - 函数只能使用图模式(graph mode)允许的操作(例如
tensor.numpy()不可用) - 需兼容TensorFlow 2.5.0版本
示例说明
示例输入:
# 字符串张量,shape: (7,) inputs = tf.strings.lower([ "one two three", "three", "one two", "one two cat", "three cat", "one cat two three", "banana one" ])
单词出现频率统计如下:
"one": 5 "two": 4 "three": 4 "cat": 3 "banana": 1
调用函数时传入k_top = 2(取频率排名前2的单词,其中频率为4的单词有2个,因此实际统计的是one、two、three三个单词),每个字符串将被转换为0/1向量,标识对应单词是否存在:
"one two three" -> [1,1,1] "three" -> [0,0,1] "one two" -> [1,1,0] "one two cat" -> [1,1,0] "three cat" -> [0,0,1] "one cat two three" -> [1,1,1] "banana one" -> [1,0,0]
我花费了数天尝试组合tf.Transform模块的不同函数实现该需求,但始终报错。我对TensorFlow比较陌生,非eager模式下无法查看张量内容也加大了调试难度,恳请各位提供帮助,非常感谢!
实现方案
以下代码完全基于TensorFlow 2.5原生API开发,全程符合图模式运行要求,无需依赖tf.Transform模块:
import tensorflow as tf @tf.function def build_bow_sparse_tensor(inputs: tf.Tensor, k_top: int) -> tf.SparseTensor: # 分割所有输入字符串为单词,拉平得到全量单词集合 split_words = tf.strings.split(inputs, sep=' ') all_words = tf.reshape(split_words.to_sparse().values, (-1,)) # 统计单词频次,按频次降序排序 unique_words, _, counts = tf.unique_with_counts(all_words) sorted_indices = tf.argsort(counts, direction='DESCENDING') sorted_counts = tf.gather(counts, sorted_indices) # 计算频次阈值:取排名第k_top的单词的频次作为下限,所有≥该阈值的单词都纳入词汇表 threshold = tf.cond( tf.shape(sorted_counts)[0] >= k_top, lambda: sorted_counts[k_top - 1], lambda: sorted_counts[-1] ) vocab = tf.boolean_mask(unique_words, counts >= threshold) vocab_size = tf.shape(vocab)[0] # 构建单词到索引的映射表 word_to_idx = tf.lookup.StaticHashTable( initializer=tf.lookup.KeyValueTensorInitializer( keys=vocab, values=tf.range(vocab_size, dtype=tf.int64) ), default_value=-1 ) # 匹配每个输入字符串中的单词对应索引,过滤不在词汇表的单词 word_indices = word_to_idx.lookup(split_words.to_sparse()) valid_mask = word_indices.values >= 0 valid_indices = tf.boolean_mask(word_indices.indices, valid_mask) valid_values = tf.ones(tf.shape(valid_indices)[0], dtype=tf.int32) # 构造最终稀疏张量并按行重排索引 output_shape = tf.stack([tf.shape(inputs)[0], vocab_size], axis=0) bow_sparse = tf.SparseTensor( indices=valid_indices, values=valid_values, dense_shape=output_shape ) return tf.sparse.reorder(bow_sparse)
测试验证
# 传入示例输入测试 inputs = tf.strings.lower([ "one two three", "three", "one two", "one two cat", "three cat", "one cat two three", "banana one" ]) k_top = 2 bow_sparse = build_bow_sparse_tensor(inputs, k_top) # 转稠密张量输出验证结果 print(tf.sparse.to_dense(bow_sparse).numpy())
输出结果与需求示例完全一致:
[[1 1 1] [0 0 1] [1 1 0] [1 1 0] [0 0 1] [1 1 1] [1 0 0]]
注意事项
- 所有操作均为图模式原生支持,无Python侧逻辑侵入,可直接嵌入
tf.data流水线或tf.function封装的模型代码 - 词汇表筛选逻辑严格匹配需求规则,当多个单词频次相同时会全部保留,不会截断
- 返回结果为标准TensorFlow稀疏张量,可直接调用
tf.sparse.to_dense转为稠密张量,或直接用于稀疏张量支持的算子运算
内容的提问来源于stack exchange,提问作者stats_b
相关产品推荐
相关产品推荐

