使用 keras tokenizer 处理不在训练集中的新单词

2024-01-26

我目前正在使用 Keras Tokenizer 创建单词索引,然后将该单词索引与导入的 GloVe 字典进行匹配以创建嵌入矩阵。然而,我遇到的问题是,这似乎破坏了使用词向量嵌入的优点之一,因为当使用经过训练的模型进行预测时,如果它遇到不在分词器的词索引中的新词,则会将其从序列中删除。

#fit the tokenizer
tokenizer = Tokenizer()
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index

#load glove embedding into a dict
embeddings_index = {}
dims = 100
glove_data = 'glove.6B.'+str(dims)+'d.txt'
f = open(glove_data)
for line in f:
    values = line.split()
    word = values[0]
    value = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = value
f.close()

#create embedding matrix
embedding_matrix = np.zeros((len(word_index) + 1, dims))
for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if embedding_vector is not None:
        # words not found in embedding index will be all-zeros.
        embedding_matrix[i] = embedding_vector[:dims]

#Embedding layer:
embedding_layer = Embedding(embedding_matrix.shape[0],
                        embedding_matrix.shape[1],
                        weights=[embedding_matrix],
                        input_length=12)

#then to make a prediction
sequence = tokenizer.texts_to_sequences(["Test sentence"])
model.predict(sequence)

那么有没有办法我仍然可以使用分词器将句子转换为数组,并且仍然尽可能多地使用 GloVe 词典中的单词,而不是只使用训练文本中显示的单词?

编辑:经过进一步考虑,我想一个选择是将一个或多个文本添加到标记器适合的文本中,其中包括手套字典中的键列表。不过,如果我想使用 tf-idf,这可能会扰乱一些统计数据。是否有更好的方法或不同的更好方法?


在 Keras Tokenizer 中,您有oov_token范围。只需选择您的令牌,未知单词就会有该令牌。

tokenizer_a = Tokenizer(oov_token=1)
tokenizer_b = Tokenizer()
tokenizer_a.fit_on_texts(["Hello world"])
tokenizer_b.fit_on_texts(["Hello world"])

Outputs

In [26]: tokenizer_a.texts_to_sequences(["Hello cruel world"])
Out[26]: [[2, 1, 3]]

In [27]: tokenizer_b.texts_to_sequences(["Hello cruel world"])
Out[27]: [[1, 2]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 keras tokenizer 处理不在训练集中的新单词 的相关文章

随机推荐