[我已经使用keras来使用预训练的单词嵌入,但是我不确定如何在scikit-learn模型上进行此操作。
我也需要在sklearn中执行此操作,因为我正在使用vecstack
集成keras顺序模型和sklearn模型。
这是我为keras模型所做的:
glove_dir = '/home/Documents/Glove'
embeddings_index = {}
f = open(os.path.join(glove_dir, 'glove.6B.200d.txt'), 'r', encoding='utf-8')
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
embedding_dim = 200
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in word_index.items():
if i < max_words:
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
model = Sequential()
model.add(Embedding(max_words, embedding_dim, input_length=maxlen))
.
.
model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False
model.compile(----)
model.fit(-----)
我对scikit-learn很陌生,据我所知,您可以在sklearn中制作模型:
lr = LogisticRegression()
lr.fit(X_train, y_train)
lr.predict(x_test)
所以,我的问题是如何在此模型中使用预训练的手套?我在哪里传递经过预先训练的手套embedding_matrix
非常感谢,非常感谢您的帮助。
您可以简单地使用Zeugma库。
您可以使用pip install zeugma
安装它,然后使用以下代码行创建和训练模型(假设corpus
是字符串列表:]
from sklearn.linear_model import LogisticRegresion
from zeugma.embeddings import EmbeddingTransformer
glove = EmbeddingTransformer('glove')
X_train = glove.transform(corpus)
model = LogisticRegression()
model.fit(X_train, y_train)
pipeline.predict(x_test)
您还可以使用其他预先训练的嵌入(完整列表here)或训练自己的嵌入(有关方法,请参见Zeugma's documentation。