使用Word2Vec确定最相似的短语



我尝试创建一个模型,该模型使用Word2vec确定另一句话的最相似句子。

这个想法是确定句子最相似的想法,我为构成此句子的单词创建了一个平均向量。

然后,我应该使用嵌入单词来预测最相似的句子。我的问题是:在创建源句子的平均向量之后,如何确定最佳的类似目标句子?

在这里代码:

import gensim
from gensim import utils
import numpy as np
import sys
from sklearn.datasets import fetch_20newsgroups
from nltk import word_tokenize
from nltk import download
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)

download('punkt') #tokenizer, run once
download('stopwords') #stopwords dictionary, run once
stop_words = stopwords.words('english')
def preprocess(text):
    text = text.lower()
    doc = word_tokenize(text)
    doc = [word for word in doc if word not in stop_words]
    doc = [word for word in doc if word.isalpha()] #restricts string to alphabetic characters only
    return doc
############  doc content  -> num label     -> string label
#note to self: texts[XXXX] -> y[XXXX] = ZZZ -> ng20.target_names[ZZZ]
# Fetch ng20 dataset
ng20 = fetch_20newsgroups(subset='all',
                          remove=('headers', 'footers', 'quotes'))
# text and ground truth labels
texts, y = ng20.data, ng20.target
corpus = [preprocess(text) for text in texts]
def filter_docs(corpus, texts, labels, condition_on_doc):
    """
    Filter corpus, texts and labels given the function condition_on_doc which takes
    a doc.
    The document doc is kept if condition_on_doc(doc) is true.
    """
    number_of_docs = len(corpus)
    print(number_of_docs)
    if texts is not None:
        texts = [text for (text, doc) in zip(texts, corpus)
                 if condition_on_doc(doc)]
    labels = [i for (i, doc) in zip(labels, corpus) if condition_on_doc(doc)]
    corpus = [doc for doc in corpus if condition_on_doc(doc)]
    print("{} docs removed".format(number_of_docs - len(corpus)))
    return (corpus, texts, labels)
corpus, texts, y = filter_docs(corpus, texts, y, lambda doc: (len(doc) != 0))
def document_vector(word2vec_model, doc):
    # remove out-of-vocabulary words
    #print("doc:")
    #print(doc)
    doc = [word for word in doc if word in word2vec_model.vocab]
    return np.mean(word2vec_model[doc], axis=0)
def has_vector_representation(word2vec_model, doc):
    """check if at least one word of the document is in the
    word2vec dictionary"""
    return not all(word not in word2vec_model.vocab for word in doc)
corpus, texts, y = filter_docs(corpus, texts, y, lambda doc: has_vector_representation(model, doc))
x =[]
for doc in corpus: #look up each doc in model
    x.append(document_vector(model, doc))

X = np.array(x) #list to array
model.most_similar(positive=X, topn=1)

只需使用余弦距离即可。它是在Scipy中实现的。

为了提高效率,您可以自己实施并预先计算X中的向量规范:

X_norm = np.linalg.norm(X, axis=1).expand_dims(0)

调用expand_dims确保尺寸得到广播。然后,对于向量Y,您可以得到最相似的方法,您可以得到最相似的:

def get_most_similar_in_X(Y):
    Y_norm = np.linalg.norm(Y, axis=1).expand_dims(1)
    similarities = np.dot(Y, X.T) / Y_norm / X_norm
    return np.argmax(distances, axis=2)

您在X中获得与 Y中最相似的向量索引。

最新更新