如何将 SOS 令牌添加到 Keras 分词器?

how to add SOS token to Keras tokenizer?

我有一个 Keras 分词器,我想在我的序列中添加句首分词,但我找不到任何关于它的信息来说明我该怎么做?

tokenizer = Tokenizer(split=' ') 

tokenizer.fit_on_texts(data)


tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'

text_tokenized = tokenizer.texts_to_sequences(data)


text_corpus_padded = pad_sequences(text_tokenized, padding='post', maxlen=100, dtype='int32')

根据您的用例(例如,解码器模型),您可以将 <sos><eos> 添加到每个句子,然后像这样对它们进行标记:

import tensorflow as tf

data = ['Hello World', 'Hello New World']
data = ['<sos> ' + x + ' <eos>' for x in data]

tokenizer = tf.keras.preprocessing.text.Tokenizer(split=' ', filters='!"#$%&()*+,-./:;=?@[\]^_`{|}~\t\n') 

tokenizer.fit_on_texts(data)

tokenizer.word_index['<pad>'] = 0
tokenizer.index_word[0] = '<pad>'

text_tokenized = tokenizer.texts_to_sequences(data)
print(text_tokenized)
print(tokenizer.word_index)
[[1, 2, 3, 4], [1, 2, 5, 3, 4]]
{'<sos>': 1, 'hello': 2, 'world': 3, '<eos>': 4, 'new': 5, '<pad>': 0}

请注意,我已从 Tokenizer 的过滤器中删除 <>,以便您可以在句子中使用这些字符。另外,检查这个 tutorial.