Finding similar documents with Word2Vec and Soft Cosine Measure

Soft Cosine Measure (SCM) [1, 4] is a promising new tool in machine learning that allows us to submit a query and return the most relevant documents. In part 1, we will show how you can compute SCM between two documents using the inner_product method. In part 2, we will use SoftCosineSimilarity to retrieve documents most similar to a query and compare the performance against other similarity measures.

First, however, we go through the basics of what Soft Cosine Measure is.

Soft Cosine Measure basics

Soft Cosine Measure (SCM) is a method that allows us to assess the similarity between two documents in a meaningful way, even when they have no words in common. It uses a measure of similarity between words, which can be derived [2] using word2vec [3] vector embeddings of words. It has been shown to outperform many of the state-of-the-art methods in the semantic text similarity task in the context of community question answering [2].

SCM is illustrated below for two very similar sentences. The sentences have no words in common, but by modeling synonymy, SCM is able to accurately measure the similarity between the two sentences. The method also uses the bag-of-words vector representation of the documents (simply put, the word's frequencies in the documents). The intution behind the method is that we compute standard cosine similarity assuming that the document vectors are expressed in a non-orthogonal basis, where the angle between two basis vectors is derived from the angle between the word2vec embeddings of the corresponding words.

This method was perhaps first introduced in the article “Soft Measure and Soft Cosine Measure: Measure of Features in Vector Space Model” by Grigori Sidorov, Alexander Gelbukh, Helena Gomez-Adorno, and David Pinto (link to PDF).

In this tutorial, we will learn how to use Gensim's SCM functionality, which consists of the inner_product method for one-off computation, and the SoftCosineSimilarity class for corpus-based similarity queries.

Note:

If you use this software, please consider citing [1] and [2].

Running this notebook

You can download this Jupyter notebook, and run it on your own computer, provided you have installed the gensim, jupyter, sklearn, pyemd, and wmd Python packages.

The notebook was run on an Ubuntu machine with an Intel core i7-6700HQ CPU 3.10GHz (4 cores) and 16 GB memory. Assuming all resources required by the notebook have already been downloaded, running the entire notebook on this machine takes about 30 minutes.


In [1]:
# Initialize logging.
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

Part 1: Computing the Soft Cosine Measure

To use SCM, we need some word embeddings first of all. You could train a word2vec (see tutorial here) model on some corpus, but we will use pre-trained word2vec embeddings.

Let's create some sentences to compare.


In [2]:
sentence_obama = 'Obama speaks to the media in Illinois'.lower().split()
sentence_president = 'The president greets the press in Chicago'.lower().split()
sentence_orange = 'Having a tough time finding an orange juice press machine?'.lower().split()

The first two sentences have very similar content, and as such the SCM should be large. Before we compute the SCM, we want to remove stopwords ("the", "to", etc.), as these do not contribute a lot to the information in the sentences.


In [3]:
# Import and download stopwords from NLTK.
from nltk.corpus import stopwords
from nltk import download
download('stopwords')  # Download stopwords list.

# Remove stopwords.
stop_words = stopwords.words('english')
sentence_obama = [w for w in sentence_obama if w not in stop_words]
sentence_president = [w for w in sentence_president if w not in stop_words]
sentence_orange = [w for w in sentence_orange if w not in stop_words]

# Prepare a dictionary and a corpus.
from gensim import corpora
documents = [sentence_obama, sentence_president, sentence_orange]
dictionary = corpora.Dictionary(documents)

# Convert the sentences into bag-of-words vectors.
sentence_obama = dictionary.doc2bow(sentence_obama)
sentence_president = dictionary.doc2bow(sentence_president)
sentence_orange = dictionary.doc2bow(sentence_orange)


2018-09-11 22:02:01,041 : INFO : 'pattern' package not found; tag filters are not available for English
2018-09-11 22:02:01,044 : INFO : adding document #0 to Dictionary(0 unique tokens: [])
2018-09-11 22:02:01,045 : INFO : built Dictionary(14 unique tokens: ['speaks', 'illinois', 'greets', 'juice', 'chicago']...) from 3 documents (total 15 corpus positions)

Now, as we mentioned earlier, we will be using some downloaded pre-trained embeddings. Note that the embeddings we have chosen here require a lot of memory. We will use the embeddings to construct a term similarity matrix that will be used by the inner_product method.


In [4]:
%%time
import gensim.downloader as api
from gensim.models import WordEmbeddingSimilarityIndex
from gensim.similarities import SparseTermSimilarityMatrix

w2v_model = api.load("glove-wiki-gigaword-50")
similarity_index = WordEmbeddingSimilarityIndex(w2v_model)
similarity_matrix = SparseTermSimilarityMatrix(similarity_index, dictionary)


2018-09-11 22:02:01,236 : INFO : loading projection weights from /home/novotny/gensim-data/glove-wiki-gigaword-50/glove-wiki-gigaword-50.gz
2018-09-11 22:02:26,984 : INFO : loaded (400000, 50) matrix from /home/novotny/gensim-data/glove-wiki-gigaword-50/glove-wiki-gigaword-50.gz
2018-09-11 22:02:26,985 : INFO : constructing a sparse term similarity matrix using <gensim.models.keyedvectors.WordEmbeddingSimilarityIndex object at 0x7f8d6e8615c0>
2018-09-11 22:02:26,986 : INFO : iterating over columns in dictionary order
2018-09-11 22:02:27,273 : INFO : constructed a sparse term similarity matrix with 11.224490% density
CPU times: user 27.8 s, sys: 2.43 s, total: 30.3 s
Wall time: 26.2 s

Let's compute SCM using the inner_product method.


In [5]:
similarity = similarity_matrix.inner_product(sentence_obama, sentence_president, normalized=True)
print('similarity = %.4f' % similarity)


similarity = 0.3790

Let's try the same thing with two completely unrelated sentences. Notice that the similarity is smaller.


In [6]:
similarity = similarity_matrix.inner_product(sentence_obama, sentence_orange, normalized=True)
print('similarity = %.4f' % similarity)


similarity = 0.1108

Part 2: Similarity queries using SoftCosineSimilarity

You can use SCM to get the most similar documents to a query, using the SoftCosineSimilarity class. Its interface is similar to what is described in the Similarity Queries Gensim tutorial.

Qatar Living unannotated dataset

Contestants solving the community question answering task in the SemEval 2016 and 2017 competitions had an unannotated dataset of 189,941 questions and 1,894,456 comments from the Qatar Living discussion forums. As our first step, we will use the same dataset to build a corpus.


In [7]:
%%time
from itertools import chain
import json
from re import sub
from os.path import isfile

import gensim.downloader as api
from gensim.utils import simple_preprocess
from nltk.corpus import stopwords
from nltk import download


download("stopwords")  # Download stopwords list.
stopwords = set(stopwords.words("english"))

def preprocess(doc):
    doc = sub(r'<img[^<>]+(>|$)', " image_token ", doc)
    doc = sub(r'<[^<>]+(>|$)', " ", doc)
    doc = sub(r'\[img_assist[^]]*?\]', " ", doc)
    doc = sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', " url_token ", doc)
    return [token for token in simple_preprocess(doc, min_len=0, max_len=float("inf")) if token not in stopwords]

corpus = list(chain(*[
    chain(
        [preprocess(thread["RelQuestion"]["RelQSubject"]), preprocess(thread["RelQuestion"]["RelQBody"])],
        [preprocess(relcomment["RelCText"]) for relcomment in thread["RelComments"]])
    for thread in api.load("semeval-2016-2017-task3-subtaskA-unannotated")]))

print("Number of documents: %d" % len(documents))


[nltk_data] Downloading package stopwords to
[nltk_data]     /home/novotny/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
Number of documents: 3
CPU times: user 2min 37s, sys: 1.62 s, total: 2min 39s
Wall time: 2min 39s

Using the corpus we have just build, we will now construct a dictionary, a TF-IDF model, a word2vec model, and a term similarity matrix.


In [8]:
%%time
from multiprocessing import cpu_count

from gensim.corpora import Dictionary
from gensim.models import TfidfModel
from gensim.models import Word2Vec
from gensim.models import WordEmbeddingSimilarityIndex
from gensim.similarities import SparseTermSimilarityMatrix

dictionary = Dictionary(corpus)
tfidf = TfidfModel(dictionary=dictionary)
w2v_model = Word2Vec(corpus, workers=cpu_count(), min_count=5, size=300, seed=12345)
similarity_index = WordEmbeddingSimilarityIndex(w2v_model.wv)
similarity_matrix = SparseTermSimilarityMatrix(similarity_index, dictionary, tfidf, nonzero_limit=100)


2018-09-11 22:06:07,973 : INFO : built Dictionary(462807 unique tokens: ['pples', 'adib', 'strangers', 'kolayaalee', 'softpoint']...) from 2274338 documents (total 40096354 corpus positions)
2018-09-11 22:06:09,432 : INFO : collecting all words and their counts
2018-09-11 22:06:17,564 : INFO : collected 462807 word types from a corpus of 40096354 raw words and 2274338 sentences
2018-09-11 22:06:17,565 : INFO : Loading a fresh vocabulary
2018-09-11 22:06:18,002 : INFO : effective_min_count=5 retains 104360 unique words (22% of original 462807, drops 358447)
2018-09-11 22:06:18,003 : INFO : effective_min_count=5 leaves 39565168 word corpus (98% of original 40096354, drops 531186)
2018-09-11 22:06:18,454 : INFO : deleting the raw counts dictionary of 462807 items
2018-09-11 22:06:18,474 : INFO : sample=0.001 downsamples 22 most-common words
2018-09-11 22:06:18,475 : INFO : downsampling leaves estimated 38552993 word corpus (97.4% of prior 39565168)
2018-09-11 22:06:18,907 : INFO : estimated required memory for 104360 words and 300 dimensions: 302644000 bytes
2018-09-11 22:06:18,908 : INFO : resetting layer weights
2018-09-11 22:06:21,082 : INFO : training model with 32 workers on 104360 vocabulary and 300 features, using sg=0 hs=0 sample=0.001 negative=5 window=5
2018-09-11 22:06:53,894 : INFO : EPOCH - 1 : training on 40096354 raw words (38515351 effective words) took 32.8s, 1174692 effective words/s
2018-09-11 22:07:27,121 : INFO : EPOCH - 2 : training on 40096354 raw words (38515107 effective words) took 33.2s, 1159858 effective words/s
2018-09-11 22:08:00,122 : INFO : EPOCH - 3 : training on 40096354 raw words (38514587 effective words) took 33.0s, 1167509 effective words/s
2018-09-11 22:08:32,976 : INFO : EPOCH - 4 : training on 40096354 raw words (38515500 effective words) took 32.8s, 1172993 effective words/s
2018-09-11 22:09:06,211 : INFO : EPOCH - 5 : training on 40096354 raw words (38515593 effective words) took 33.2s, 1159566 effective words/s
2018-09-11 22:09:06,212 : INFO : training on a 200481770 raw words (192576138 effective words) took 165.1s, 1166216 effective words/s
2018-09-11 22:09:06,637 : INFO : constructing a sparse term similarity matrix using <gensim.models.keyedvectors.WordEmbeddingSimilarityIndex object at 0x7f8cde1dc9b0>
2018-09-11 22:09:06,657 : INFO : iterating over columns in tf-idf order
2018-09-11 22:25:34,416 : INFO : constructed a sparse term similarity matrix with 0.003654% density
CPU times: user 4h 38min 32s, sys: 4h 24min 33s, total: 9h 3min 5s
Wall time: 20min 43s

Evaluation

Next, we will load the validation and test datasets that were used by the SemEval 2016 and 2017 contestants. The datasets contain 208 original questions posted by the forum members. For each question, there is a list of 10 threads with a human annotation denoting whether or not the thread is relevant to the original question. Our task will be to order the threads so that relevant threads rank above irrelevant threads.


In [9]:
datasets = api.load("semeval-2016-2017-task3-subtaskBC")

Finally, we will perform an evaluation to compare three unsupervised similarity measures – the Soft Cosine Measure, two different implementations of the Word Mover's Distance, and standard cosine similarity. We will use the Mean Average Precision (MAP) as an evaluation measure and 10-fold cross-validation to get an estimate of the variance of MAP for each similarity measure.


In [10]:
from math import isnan
from time import time

from gensim.similarities import MatrixSimilarity, WmdSimilarity, SoftCosineSimilarity
import numpy as np
from sklearn.model_selection import KFold
from wmd import WMD

def produce_test_data(dataset):
    for orgquestion in datasets[dataset]:
        query = preprocess(orgquestion["OrgQSubject"]) + preprocess(orgquestion["OrgQBody"])
        documents = [
            preprocess(thread["RelQuestion"]["RelQSubject"]) + preprocess(thread["RelQuestion"]["RelQBody"])
            for thread in orgquestion["Threads"]]
        relevance = [
            thread["RelQuestion"]["RELQ_RELEVANCE2ORGQ"] in ("PerfectMatch", "Relevant")
            for thread in orgquestion["Threads"]]
        yield query, documents, relevance

def cossim(query, documents):
    # Compute cosine similarity between the query and the documents.
    query = tfidf[dictionary.doc2bow(query)]
    index = MatrixSimilarity(
        tfidf[[dictionary.doc2bow(document) for document in documents]],
        num_features=len(dictionary))
    similarities = index[query]
    return similarities

def softcossim(query, documents):
    # Compute Soft Cosine Measure between the query and the documents.
    query = tfidf[dictionary.doc2bow(query)]
    index = SoftCosineSimilarity(
        tfidf[[dictionary.doc2bow(document) for document in documents]],
        similarity_matrix)
    similarities = index[query]
    return similarities

def wmd_gensim(query, documents):
    # Compute Word Mover's Distance as implemented in PyEMD by William Mayner
    # between the query and the documents.
    index = WmdSimilarity(documents, w2v_model)
    similarities = index[query]
    return similarities

def wmd_relax(query, documents):
    # Compute Word Mover's Distance as implemented in WMD by Source{d}
    # between the query and the documents.
    words = [word for word in set(chain(query, *documents)) if word in w2v_model.wv]
    indices, words = zip(*sorted((
        (index, word) for (index, _), word in zip(dictionary.doc2bow(words), words))))
    query = dict(tfidf[dictionary.doc2bow(query)])
    query = [
        (new_index, query[dict_index])
        for new_index, dict_index in enumerate(indices)
        if dict_index in query]
    documents = [dict(tfidf[dictionary.doc2bow(document)]) for document in documents]
    documents = [[
        (new_index, document[dict_index])
        for new_index, dict_index in enumerate(indices)
        if dict_index in document] for document in documents]
    embeddings = np.array([w2v_model.wv[word] for word in words], dtype=np.float32)
    nbow = dict(((index, list(chain([None], zip(*document)))) for index, document in enumerate(documents)))
    nbow["query"] = tuple([None] + list(zip(*query)))
    distances = WMD(embeddings, nbow, vocabulary_min=1).nearest_neighbors("query")
    similarities = [-distance for _, distance in sorted(distances)]
    return similarities

strategies = {
    "cossim" : cossim,
    "softcossim": softcossim,
    "wmd-gensim": wmd_gensim,
    "wmd-relax": wmd_relax}

def evaluate(split, strategy):
    # Perform a single round of evaluation.
    results = []
    start_time = time()
    for query, documents, relevance in split:
        similarities = strategies[strategy](query, documents)
        assert len(similarities) == len(documents)
        precision = [
            (num_correct + 1) / (num_total + 1) for num_correct, num_total in enumerate(
                num_total for num_total, (_, relevant) in enumerate(
                    sorted(zip(similarities, relevance), reverse=True)) if relevant)]
        average_precision = np.mean(precision) if precision else 0.0
        results.append(average_precision)
    return (np.mean(results) * 100, time() - start_time)

def crossvalidate(args):
    # Perform a cross-validation.
    dataset, strategy = args
    test_data = np.array(list(produce_test_data(dataset)))
    kf = KFold(n_splits=10)
    samples = []
    for _, test_index in kf.split(test_data):
        samples.append(evaluate(test_data[test_index], strategy))
    return (np.mean(samples, axis=0), np.std(samples, axis=0))

In [11]:
%%time
from multiprocessing import Pool

args_list = [
    (dataset, technique)
    for dataset in ("2016-test", "2017-test")
    for technique in ("softcossim", "wmd-gensim", "wmd-relax", "cossim")]
with Pool() as pool:
    results = pool.map(crossvalidate, args_list)


CPU times: user 2.14 s, sys: 5.08 s, total: 7.22 s
Wall time: 2min 51s

The table below shows the pointwise estimates of means and standard variances for MAP scores and elapsed times. Baselines and winners for each year are displayed in bold. We can see that the Soft Cosine Measure gives a strong performance on both the 2016 and the 2017 dataset.


In [12]:
from IPython.display import display, Markdown

output = []
baselines = [
    (("2016-test", "**Winner (UH-PRHLT-primary)**"), ((76.70, 0), (0, 0))),
    (("2016-test", "**Baseline 1 (IR)**"), ((74.75, 0), (0, 0))),
    (("2016-test", "**Baseline 2 (random)**"), ((46.98, 0), (0, 0))),
    (("2017-test", "**Winner (SimBow-primary)**"), ((47.22, 0), (0, 0))),
    (("2017-test", "**Baseline 1 (IR)**"), ((41.85, 0), (0, 0))),
    (("2017-test", "**Baseline 2 (random)**"), ((29.81, 0), (0, 0)))]
table_header = ["Dataset | Strategy | MAP score | Elapsed time (sec)", ":---|:---|:---|---:"]
for row, ((dataset, technique), ((mean_map_score, mean_duration), (std_map_score, std_duration))) \
        in enumerate(sorted(chain(zip(args_list, results), baselines), key=lambda x: (x[0][0], -x[1][0][0]))):
    if row % (len(strategies) + 3) == 0:
        output.extend(chain(["\n"], table_header))
    map_score = "%.02f ±%.02f" % (mean_map_score, std_map_score)
    duration = "%.02f ±%.02f" % (mean_duration, std_duration) if mean_duration else ""
    output.append("%s|%s|%s|%s" % (dataset, technique, map_score, duration))

display(Markdown('\n'.join(output)))


Dataset Strategy MAP score Elapsed time (sec)
2016-test softcossim 77.15 ±10.83 4.48 ±0.56
2016-test Winner (UH-PRHLT-primary) 76.70 ±0.00
2016-test cossim 76.45 ±10.40 0.25 ±0.04
2016-test wmd-gensim 76.15 ±11.51 13.79 ±1.39
2016-test Baseline 1 (IR) 74.75 ±0.00
2016-test wmd-relax 72.03 ±11.33 0.34 ±0.07
2016-test Baseline 2 (random) 46.98 ±0.00
Dataset Strategy MAP score Elapsed time (sec)
2017-test Winner (SimBow-primary) 47.22 ±0.00
2017-test wmd-relax 45.04 ±15.44 0.39 ±0.07
2017-test cossim 44.38 ±14.71 0.29 ±0.05
2017-test softcossim 44.25 ±15.68 4.89 ±0.80
2017-test wmd-gensim 44.08 ±15.96 16.69 ±1.90
2017-test Baseline 1 (IR) 41.85 ±0.00
2017-test Baseline 2 (random) 29.81 ±0.00

References

  1. Grigori Sidorov et al. Soft Similarity and Soft Cosine Measure: Similarity of Features in Vector Space Model, 2014. (link to PDF)
  2. Delphine Charlet and Geraldine Damnati, SimBow at SemEval-2017 Task 3: Soft-Cosine Semantic Similarity between Questions for Community Question Answering, 2017. (link to PDF)
  3. Thomas Mikolov et al. Efficient Estimation of Word Representations in Vector Space, 2013. (link to PDF)
  4. Vít Novotný. Implementation Notes for the Soft Cosine Measure, 2018. (link to PDF)