tensorflow - Tensorflow 文本分词器不正确分词
问题描述
我正在尝试TF Tokenizer
用于 NLP 模型
from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer = Tokenizer(num_words=200, split=" ")
sample_text = ["This is a sample sentence1 created by sample person AB.CDEFGHIJKLMNOPQRSTUVWXYZ",
"This is another sample sentence1 created by another sample person AB.CDEFGHIJKLMNOPQRSTUVWXYZ"]
tokenizer.fit_on_texts(sample_text)
print (tokenizer.texts_to_sequences(["sample person AB.CDEFGHIJKLMNOPQRSTUVWXYZ"]))
操作:
[[1, 7, 8, 9]]
字索引:
print(tokenizer.index_word[8]) ===> 'ab'
print(tokenizer.index_word[9]) ===> 'cdefghijklmnopqrstuvwxyz'
问题是在这种情况下tokenizer
创建令牌。.
我正在给出split = " "
,Tokenizer
所以我期待以下操作:
[[1,7,8]], where tokenizer.index_word[8] should be 'ab.cdefghijklmnopqrstuvwxyz'
正如我希望标记器words
基于space (" ")
而不是基于任何special characters
如何tokenizer
仅在 上创建创建令牌spaces
?
解决方案
Tokenizer
接受另一个称为filter
当前默认为所有 ascii 标点符号 ( filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n'
)的参数。在标记化期间,其中包含的所有字符filter
都将替换为指定的split
字符串。
如果您查看源代码,Tokenizer
特别是方法fit_on_texts,您会看到它使用函数text_to_word_sequence接收filter
字符并认为它们与split
它接收的相同:
def text_to_word_sequence(... ):
...
translate_dict = {c: split for c in filters}
translate_map = maketrans(translate_dict)
text = text.translate(translate_map)
seq = text.split(split)
return [i for i in seq if i]
因此,为了不拆分指定的split
,只需将空字符串传递给filter
参数
推荐阅读
- wordpress - 如何将 apache2 链接到 wordpress docker 容器?
- javascript - 我如何创建一个菜单,用户可以在其中插入和删除认为他/她添加的内容?在 Eclipse 中的 javascript google-appengine
- wagtail - Wagtail:如何订购片段
- python-3.x - Python MultiProcessing 使 tkinter GUI 再次出现
- linux - 提取在 2 个图像之间变化的像素并使用图像魔法转换保存到新的图像,同时保持原始颜色
- javascript - 如何用 Jest 测试 void 方法
- javascript - 如何移动创建的内容
成一个 不移动整体 并不断创造元素 ? - javascript - 将路由存储在文件中并导入 App.js
- javascript - onClick 和 addEventListner?没有任何作用
- java - JUnit5 和 IntelliJ IDEA:使用反引号和括号命名 Kotlin 函数