Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7072047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:45:40+00:00 2026-05-28T05:45:40+00:00

I am looking at working on an NLP project, in any programming language (though

  • 0

I am looking at working on an NLP project, in any programming language (though Python will be my preference).

I want to take two documents and determine how similar they are.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:45:41+00:00Added an answer on May 28, 2026 at 5:45 am

    The common way of doing this is to transform the documents into TF-IDF vectors and then compute the cosine similarity between them. Any textbook on information retrieval (IR) covers this. See esp. Introduction to Information Retrieval, which is free and available online.

    Computing Pairwise Similarities

    TF-IDF (and similar text transformations) are implemented in the Python packages Gensim and scikit-learn. In the latter package, computing cosine similarities is as easy as

    from sklearn.feature_extraction.text import TfidfVectorizer
    
    documents = [open(f).read() for f in text_files]
    tfidf = TfidfVectorizer().fit_transform(documents)
    # no need to normalize, since Vectorizer will return normalized tf-idf
    pairwise_similarity = tfidf * tfidf.T
    

    or, if the documents are plain strings,

    >>> corpus = ["I'd like an apple", 
    ...           "An apple a day keeps the doctor away", 
    ...           "Never compare an apple to an orange", 
    ...           "I prefer scikit-learn to Orange", 
    ...           "The scikit-learn docs are Orange and Blue"]                                                                                                                                                                                                   
    >>> vect = TfidfVectorizer(min_df=1, stop_words="english")                                                                                                                                                                                                   
    >>> tfidf = vect.fit_transform(corpus)                                                                                                                                                                                                                       
    >>> pairwise_similarity = tfidf * tfidf.T 
    

    though Gensim may have more options for this kind of task.

    See also this question.

    [Disclaimer: I was involved in the scikit-learn TF-IDF implementation.]

    Interpreting the Results

    From above, pairwise_similarity is a Scipy sparse matrix that is square in shape, with the number of rows and columns equal to the number of documents in the corpus.

    >>> pairwise_similarity                                                                                                                                                                                                                                      
    <5x5 sparse matrix of type '<class 'numpy.float64'>'
        with 17 stored elements in Compressed Sparse Row format>
    

    You can convert the sparse array to a NumPy array via .toarray() or .A:

    >>> pairwise_similarity.toarray()                                                                                                                                                                                                                            
    array([[1.        , 0.17668795, 0.27056873, 0.        , 0.        ],
           [0.17668795, 1.        , 0.15439436, 0.        , 0.        ],
           [0.27056873, 0.15439436, 1.        , 0.19635649, 0.16815247],
           [0.        , 0.        , 0.19635649, 1.        , 0.54499756],
           [0.        , 0.        , 0.16815247, 0.54499756, 1.        ]])
    

    Let’s say we want to find the document most similar to the final document, "The scikit-learn docs are Orange and Blue". This document has index 4 in corpus. You can find the index of the most similar document by taking the argmax of that row, but first you’ll need to mask the 1’s, which represent the similarity of each document to itself. You can do the latter through np.fill_diagonal(), and the former through np.nanargmax():

    >>> import numpy as np     
                                                                                                                                                                                                                                      
    >>> arr = pairwise_similarity.toarray()     
    >>> np.fill_diagonal(arr, np.nan)                                                                                                                                                                                                                            
                                                                                                                                                                                                                     
    >>> input_doc = "The scikit-learn docs are Orange and Blue"                                                                                                                                                                                                  
    >>> input_idx = corpus.index(input_doc)                                                                                                                                                                                                                      
    >>> input_idx                                                                                                                                                                                                                                                
    4
    
    >>> result_idx = np.nanargmax(arr[input_idx])                                                                                                                                                                                                                
    >>> corpus[result_idx]                                                                                                                                                                                                                                       
    'I prefer scikit-learn to Orange'
    

    Note: the purpose of using a sparse matrix is to save (a substantial amount of space) for a large corpus & vocabulary. Instead of converting to a NumPy array, you could do:

    >>> n, _ = pairwise_similarity.shape                                                                                                                                                                                                                         
    >>> pairwise_similarity[np.arange(n), np.arange(n)] = -1.0
    >>> pairwise_similarity[input_idx].argmax()                                                                                                                                                                                                                  
    3
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on a process that will perform natural language processing (NLP) on one--and
I'm looking at working on a project which uses C#.NET (sitting on a windows
I'm working with someone who's looking to get back into programming after several years
While working on a C++ project, I was looking for a third party library
Looking for some help on some names for a project I'm currently working on.
I am working on my Master's project and I am looking for a substantial
I am working on a project which features one database table looking like this
Am working on a flex project I am looking to provide some UI functionality
I have been looking at Padrino for a project I am working on, and
I'm working on a survey project and am looking for the best way to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.