Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gensim: custom similarity measure

Using gensim, I want to calculate the similarity within a list of documents. This library is excellent at handling the amounts of data that I have got. The documents are all reduced to timestamps and I have got a function time_similarity to compare them. gensim however, uses the cosine similarity.

I am wondering if anyone has attemted this before or has a different solution.

like image 679
Simon Avatar asked Jun 27 '16 12:06

Simon


Video Answer


1 Answers

It is possible to do this by inheriting from the interface SimilarityABC. I did not find any documentation for this but it looks like it has been done before to define Word Mover Distance similarity. Here is a generic way to do this. You can likely make it more efficient by specializing to the similarity measure you care about.

import numpy
from gensim import interfaces

class CustomSimilarity(interfaces.SimilarityABC):

    def __init__(self, corpus, custom_similarity, num_best=None, chunksize=256):
        self.corpus = corpus
        self.custom_similarity = custom_similarity
        self.num_best = num_best
        self.chunksize = chunksize
        self.normalize = False

    def get_similarities(self, query):
        """
        **Do not use this function directly; use the self[query] syntax instead.**
        """
        if isinstance(query, numpy.ndarray):
            # Convert document indexes to actual documents.
            query = [self.corpus[i] for i in query]
        if not isinstance(query[0], list):
            query = [query]
        n_queries = len(query)
        result = []
        for qidx in range(n_queries):
            qresult = [self.custom_similarity(document, query[qidx]) for document in self.corpus]
            qresult = numpy.array(qresult)
            result.append(qresult)
        if len(result) == 1:
            # Only one query.
            result = result[0]
        else:
            result = numpy.array(result)
        return result

To implement a custom similarity:

def overlap_sim(doc1, doc2):
    # similarity defined by the number of common words
    return len(set(doc1) & set(doc2))
corpus = [['cat', 'dog'], ['cat', 'bird'], ['dog']]
cs = CustomSimilarity(corpus, overlap_sim, num_best=2)
print(cs[['bird', 'cat', 'frog']])

This outputs [(1, 2.0), (0, 1.0)].

like image 86
xeqql Avatar answered Sep 27 '22 21:09

xeqql