Calculate Cosine Similarity in PyTorch

This post explains how to calculate Cosine Similarity in PyTorch. torch.nn.functional module provides cosine_similarity method for calculating Cosine Similarity

  • Import modules
  • 
    
    import torch
    import torch.nn.functional as F
    
    
  • Create two random tesnors
  • 
    
    tensor1 = torch.randn(50)
    
    tensor2 = torch.randn(50)
    
    
  • Calculate Cosine Similarity
  • 
    
    
    cosine_similarity_value = F.cosine_similarity(tensor1, tensor2, dim=0)
    
    print(cosine_similarity_value)
    
    #### Output ####
    tensor(-0.2427)
    
    
    

    Category: PyTorch