{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Shashank Kapadia",
  "title_listed": "5 Data Similarity Metrics",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/5-data-similarity-metrics-f358a560855f/",
  "publish_date": "2022-12-27",
  "corpus_stage": "",
  "notes": "",
  "id": "6541e4c5eaf0",
  "collected_at": "2026-10-02T09:58:38",
  "title": "5 Data Similarity Metrics | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# 5 Data Similarity Metrics\nUnderstanding similarity metrics in data analysis and machine learning: A comprehensive guide\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nDecember 27, 20227 min read\n![Two similar faces next to each other \\(data similarity concept\\)](../images/000.jpg)\nPhoto by Alexander Grey on Unsplash \n_Preface: This article presents a summary of information about the given topic. It should not be considered original research. The information and code included in this article may be influenced by things I have read or seen in the past from various online articles, research papers, books, and open-source code._\n## Introduction\nSimilarity metrics are a vital tool in many data analysis and machine learning tasks, allowing us to compare and evaluate the similarity between different pieces of data. Many different metrics are available, each with pros and cons and suitable for different data types and tasks.\nThis article will explore some of the most common similarity metrics and compare their strengths and weaknesses. By understanding the characteristics and limitations of these metrics, we can choose the most appropriate one for our specific needs and ensure the accuracy and relevance of our results.\n## Euclidean distance\nThis metric calculates the straight-line distance between two points in n-dimensional space. It is often used for continuous numerical data and is easy to understand and implement. However, it can be sensitive to outliers and does not account for the relative importance of different features.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\npython\n\n```\nfrom scipy.spatial import distance\n\n# Calculate Euclidean distance between two points\npoint1 = [1, 2, 3]\npoint2 = [4, 5, 6]\n\n# Use the euclidean function from scipy's distance module to calculate the Euclidean distance\neuclidean_distance = distance.euclidean(point1, point2)\n```\n\n## Manhattan distance\nThis metric calculates the distance between two points by considering the absolute differences of their coordinates in each dimension and summing them. It is less sensitive to outliers than Euclidean distance, but it may not accurately reflect the actual distance between points in some cases.\npython\n\n```\nfrom scipy.spatial import distance\n\n# Calculate Manhattan distance between two points\npoint1 = [1, 2, 3]\npoint2 = [4, 5, 6]\n\n# Use the cityblock function from scipy's distance module to calculate the Manhattan distance\nmanhattan_distance = distance.cityblock(point1, point2)\n\n# Print the result\nprint(\"Manhattan Distance between the given two points: \" + \\\n      str(manhattan_distance))\n```\n\n## Cosine similarity\nThis metric calculates the similarity between two vectors by considering their angle. It is often used for text data and is resistant to changes in the magnitude of the vectors. However, it does not consider the relative importance of different features.\npython\n\n```\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# Calculate cosine similarity between two vectors\nvector1 = [1, 2, 3]\nvector2 = [4, 5, 6]\n\n# Use the cosine_similarity function from scikit-learn to calculate the similarity\ncosine_sim = cosine_similarity([vector1], [vector2])[0][0]\n\n# Print the result\nprint(\"Cosine Similarity between the given two vectors: \" + \\\n      str(cosine_sim))\n```\n\n## Jaccard similarity\nThis metric calculates the similarity between two sets by considering the size of their intersection and union. It is often used for categorical data and is resistant to changes in the size of the sets. However, it does not consider the sets' order or frequency of elements.\npython\n\n```\ndef jaccard_similarity(list1, list2):\n    \"\"\"\n    Calculates the Jaccard similarity between two lists.\n    \n    Parameters:\n    list1 (list): The first list to compare.\n    list2 (list): The second list to compare.\n    \n    Returns:\n    float: The Jaccard similarity between the two lists.\n    \"\"\"\n    # Convert the lists to sets for easier comparison\n    s1 = set(list1)\n    s2 = set(list2)\n    \n    # Calculate the Jaccard similarity by taking the length of the intersection of the sets\n    # and dividing it by the length of the union of the sets\n    return float(len(s1.intersection(s2)) / len(s1.union(s2)))\n\n# Calculate Jaccard similarity between two sets\nset1 = [1, 2, 3]\nset2 = [2, 3, 4]\njaccard_sim = jaccard_similarity(set1, set2)\n\n# Print the result\nprint(\"Jaccard Similarity between the given two sets: \" + \\\n      str(jaccard_sim))\n```\n\n## Pearson correlation coefficient\nThis metric calculates the linear correlation between two variables. It is often used for continuous numerical data and considers the relative importance of different features. However, it may not accurately reflect non-linear relationships.\npython\n\n```\nimport numpy as np\n\n# Calculate Pearson correlation coefficient between two variables\nx = [1, 2, 3, 4]\ny = [2, 3, 4, 5]\n\n# Numpy corrcoef function to calculate the Pearson correlation coefficient and p-value\npearson_corr = np.corrcoef(x, y)[0][1]\n\n# Print the result\nprint(\"Pearson Correlation between the given two variables: \" + \\\n      str(pearson_corr))\n```\n\nNow that we have reviewed the basics of these distance metrics, let’s consider a practical scenario and apply them to compare the results.\n## Scenario\nSuppose we have 5 items with numerical attributes and we want to compare the similarities between these products in order to facilitate applications such as clustering, classification, or perhaps, recommendations.\nThe following code computes the similarity metrics for the given products and their attributes using various distance metrics and then plots the results in a heat map for evaluation.\npython\n\n```\nimport numpy as np\nimport seaborn as sns\nimport random\nimport matplotlib.pyplot as plt\nimport pprint\n\ndef calculate_similarities(products):\n    \"\"\"Calculate the similarity measures between all pairs of products.\n    \n    Parameters\n    ----------\n    products : list\n        A list of dictionaries containing the attributes of the products.\n    \n    Returns\n    -------\n    euclidean_similarities : numpy array\n        An array containing the Euclidean distance between each pair of products.\n    manhattan_distances : numpy array\n        An array containing the Manhattan distance between each pair of products.\n    cosine_similarities : numpy array\n        An array containing the cosine similarity between each pair of products.\n    jaccard_similarities : numpy array\n        An array containing the Jaccard index between each pair of products.\n    pearson_similarities : numpy array\n        An array containing the Pearson correlation coefficient between each pair of products.\n    \"\"\"\n    # Initialize arrays to store the similarity measures\n    euclidean_similarities = np.zeros((len(products), len(products)))\n    manhattan_distances = np.zeros((len(products), len(products)))\n    cosine_similarities = np.zeros((len(products), len(products)))\n    jaccard_similarities = np.zeros((len(products), len(products)))\n    pearson_similarities = np.zeros((len(products), len(products)))\n\n    # Calculate all the similarity measures in a single loop\n    for i in range(len(products)):\n        for j in range(i+1, len(products)):\n            p1 = products[i]['attributes']\n            p2 = products[j]['attributes']\n\n            # Calculate Euclidean distance\n            euclidean_similarities[i][j] = distance.euclidean(p1, p2)\n            euclidean_similarities[j][i] = euclidean_similarities[i][j]\n\n            # Calculate Manhattan distance\n            manhattan_distances[i][j] = distance.cityblock(p1, p2)\n            manhattan_distances[j][i] = manhattan_distances[i][j]\n\n            # Calculate cosine similarity\n            cosine_similarities[i][j] = cosine_similarity([p1], [p2])[0][0]\n            cosine_similarities[j][i] = cosine_similarities[i][j]\n\n            # Calculate Jaccard index\n            jaccard_similarities[i][j] = jaccard_similarity(p1, p2)\n            jaccard_similarities[j][i] = jaccard_similarities[i][j]\n\n            # Calculate Pearson correlation coefficient\n            pearson_similarities[i][j] = np.corrcoef(p1, p2)[0][1]\n            pearson_similarities[j][i] = pearson_similarities[i][j]\n            \n    return euclidean_similarities, manhattan_distances, cosine_similarities, jaccard_similarities, pearson_similarities\n\ndef plot_similarities(similarities_list, labels, titles):\n    \"\"\"Plot the given similarities as heatmaps in subplots.\n    \n    Parameters\n    ----------\n    similarities_list : list of numpy arrays\n        A list of arrays containing the similarities between the products.\n    labels : list\n        A list of strings containing the labels for the products.\n    titles : list\n        A list of strings containing the titles for each plot.\n    \n    Returns\n    -------\n    None\n        This function does not return any values. It only plots the heatmaps.\n    \"\"\"\n    # Set up the plot\n    fig, ax = plt.subplots(nrows=1, \n                           ncols=len(similarities_list), figsize=(6*len(similarities_list), 6/1.680))\n\n    for i, similarities in enumerate(similarities_list):\n        # Plot the heatmap\n        sns.heatmap(similarities, xticklabels=labels, yticklabels=labels, ax=ax[i])\n        ax[i].set_title(titles[i])\n        ax[i].set_xlabel(\"Product\")\n        ax[i].set_ylabel(\"Product\")\n    \n    # Show the plot\n    plt.show()\n\n# Define the products and their attributes\nproducts = [\n    {'name': 'Product 1', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 2', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 3', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 4', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 5', 'attributes': random.sample(range(1, 11), 5)}\n]\n\npprint.pprint(products)\n\neuclidean_similarities, manhattan_distances, \\\ncosine_similarities, jaccard_similarities, \\\npearson_similarities = calculate_similarities(products)\n\n# Set the labels for the x-axis and y-axis\nproduct_labels = [product['name'] for product in products]\n\n# List of similarity measures and their titles\nsimilarities_list = [euclidean_similarities, cosine_similarities, pearson_similarities, \n                     jaccard_similarities, manhattan_distances]\ntitles = [\"Euclidean Distance\", \"Cosine Similarity\", \"Pearson Correlation Coefficient\", \n          \"Jaccard Index\", \"Manhattan Distance\"]\n\n# Plot the heatmaps\nplot_similarities(similarities_list, product_labels, titles)\n```\n\n![](../images/001.png)\nAs we can see from the charts, each similarity metric produces a heat map that represents different similarities between the products, and on a different scale. While each similarity metric can be used to interpret whether two products are similar or not based on the metric’s value, it is difficult to determine a true measure of similarity when comparing the results across different distance metrics.\n### How to choose the correct **metric**\nThere is no single “true” answer when it comes to choosing a similarity metric, as different metrics are better suited for different types of data and different analysis goals. However, there are some factors that can help narrow down the possible metrics that might be appropriate for a given situation. Some things to consider when choosing a similarity metric include:\n  * **The type of data** : Some metrics are more appropriate for continuous data, while others are better suited for categorical or binary data.\n  * **The characteristics of the data** : Different metrics are sensitive to different aspects of the data, such as the magnitudes of differences between attributes or the angles between attributes. Consider which characteristics of the data are most important to your analysis and choose a similarity metric that is sensitive to these characteristics.\n  * **The goals of your analysis** : Different metrics can highlight different patterns or relationships in the data, so consider what you are trying to learn from your analysis and choose a distance metric that is well-suited to this purpose.\n\n\nPersonally, I often use the following chart as a starting point when choosing a similarity metric.\n![](../images/body-fd5eef7dd70ff988d0f8.png)\nAgain, it is important to carefully consider the data type and characteristics when selecting a similarity metric, as well as the specific goals of the analysis.\nAll of the code used in this article can be found at [Jupyter Notebook](https://github.com/kapadias/medium-articles/blob/master/general-data-science/similarities-measures/similarity-measures.ipynb).\n_Thanks for reading. If you have any feedback, please feel to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (shmkapadia[at]gmail[dot]com)_.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Distance Metrics](https://towardsdatascience.com/tag/distance-metrics/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Similarity Metrics](https://towardsdatascience.com/tag/similarity-metrics/)[Statistics](https://towardsdatascience.com/tag/statistics/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&title=5%20Data%20Similarity%20Metrics)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&title=5%20Data%20Similarity%20Metrics)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&text=5%20Data%20Similarity%20Metrics)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpg)](https://towardsdatascience.com/solving-a-tennis-refactoring-challenge-in-python-using-solid-f1282f85e7e0/)\n## [Solving a Tennis Refactoring Challenge in Python using SOLID](https://towardsdatascience.com/solving-a-tennis-refactoring-challenge-in-python-using-solid-f1282f85e7e0/)\n[Software Engineering](https://towardsdatascience.com/category/programming/software-engineering/)\nA step-by-step illustration of how to use SOLID to solve a refactoring challenge\n[Tomer Gabay](https://towardsdatascience.com/author/tomergabay/)\nFebruary 5, 20249 min read\n  * [![](../images/003.png)](https://towardsdatascience.com/techniques-for-dimensionality-reduction-927a10135356/)\n## [Techniques for Dimensionality Reduction](https://towardsdatascience.com/techniques-for-dimensionality-reduction-927a10135356/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA guide for employing dimensionality reduction to improve an AI model's efficacy\n[Matthew Connelly](https://towardsdatascience.com/author/matthewconnelly/)\nJune 13, 202110 min read\n  * [![](../images/004.jpg)](https://towardsdatascience.com/geospatial-exploratory-data-analysis-with-geopandas-and-duckdb/)\n## [Geospatial exploratory data analysis with GeoPandas and DuckDB](https://towardsdatascience.com/geospatial-exploratory-data-analysis-with-geopandas-and-duckdb/)\n[Programming](https://towardsdatascience.com/category/programming/)\nWhich UK city has the safest drivers?\n[Thomas Reid](https://towardsdatascience.com/author/thomas_reid/)\nDecember 15, 202513 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/conditional-probabilities-seattle-rain-and-tricky-friends-aa1f33c20e29/)\n## [Conditional Probabilities, Seattle Rain, And Tricky Friends](https://towardsdatascience.com/conditional-probabilities-seattle-rain-and-tricky-friends-aa1f33c20e29/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nBetter Understand Probability By Tackling This Data Science Interview Question (With Python)\n[Tony Yiu](https://towardsdatascience.com/author/tonester524/)\nMay 31, 20208 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/analysis-of-variance-anova-8dc889d2fc3a/)\n## [Analysis of Variance - ANOVA](https://towardsdatascience.com/analysis-of-variance-anova-8dc889d2fc3a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCollege Statistics with Python\n[Luís Roque](https://towardsdatascience.com/author/luisroque/)\nAugust 3, 20215 min read\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/writing-llms-in-rust-looking-for-an-efficient-matrix-multiplication-e9539b0cb9d3/)\n## [Writing LLMs in Rust: Looking for an Efficient Matrix Multiplication](https://towardsdatascience.com/writing-llms-in-rust-looking-for-an-efficient-matrix-multiplication-e9539b0cb9d3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHere are the lessons I learned and how I am writing llm.rust and tackling the matrix multiplication problem\n[Stefano Bosisio](https://towardsdatascience.com/author/stefanobosisio1/)\nNovember 14, 202415 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/how-to-chunk-text-data-a-comparative-analysis-3858c4a0997a/)\n## [How to Chunk Text Data - A Comparative Analysis](https://towardsdatascience.com/how-to-chunk-text-data-a-comparative-analysis-3858c4a0997a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExploring and comparing distinct approaches to text chunking.\n[Solano Todeschini](https://towardsdatascience.com/author/solano-todeschini/)\nJuly 20, 202318 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/keeping-up-data-appearances-e5225d7620b0/)\n## [Keeping up (data) appearances](https://towardsdatascience.com/keeping-up-data-appearances-e5225d7620b0/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nData is the fuel to creating value for your customers and its application is far...\n[Chanade Hemming](https://towardsdatascience.com/author/chanadehemming/)\nMay 19, 20219 min read\n  * [![](../images/010.jpeg)](https://towardsdatascience.com/fine-tune-llama-3-1-ultra-efficiently-with-unsloth-7196c7165bab/)\n## [Fine-Tune Llama 3.1 Ultra-Efficiently with Unsloth](https://towardsdatascience.com/fine-tune-llama-3-1-ultra-efficiently-with-unsloth-7196c7165bab/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nA beginner's guide to state-of-the-art supervised fine-tuning\n[Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\nJuly 29, 202412 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "5 Data Similarity Metrics | Towards Data Science",
    "description": "Understanding similarity metrics in data analysis and machine learning: A comprehensive guide",
    "keywords": null,
    "author": "Shashank Kapadia",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "5 Data Similarity Metrics",
    "og:description": "Understanding similarity metrics in data analysis and machine learning: A comprehensive guide",
    "og:url": "https://towardsdatascience.com/5-data-similarity-metrics-f358a560855f/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Data-similarity.jpg",
    "og:image:width": "1400",
    "og:image:height": "933",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Shashank Kapadia",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "7 min read",
    "article:published_time": "2022-12-27T18:04:27.000Z",
    "article:modified_time": "2022-12-27T18:04:27.000Z",
    "article:author": "https://towardsdatascience.com/author/shashank kapadia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_000.txt",
      "chars": 275
    },
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_001.txt",
      "chars": 388
    },
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_002.txt",
      "chars": 394
    },
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_003.txt",
      "chars": 845
    },
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_004.txt",
      "chars": 358
    },
    {
      "language": "txt",
      "file": "attachments/6541e4c5eaf0/code/block_005.txt",
      "chars": 4823
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:55:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:55:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:52Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shashank kapadia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/distance-metrics/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/similarity-metrics/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/statistics/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/solving-a-tennis-refactoring-challenge-in-python-using-solid-f1282f85e7e0/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/software-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/tomergabay/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/techniques-for-dimensionality-reduction-927a10135356/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/matthewconnelly/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/geospatial-exploratory-data-analysis-with-geopandas-and-duckdb/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://github.com/kapadias/medium-articles/blob/master/general-data-science/similarities-measures/similarity-measures.ipynb"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/shashankkapadia/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=5+Data+Similarity+Metrics&u=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=5+Data+Similarity+Metrics&url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=5+Data+Similarity+Metrics&url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:29:25Z",
  "source_url": "https://towardsdatascience.com/5-data-similarity-metrics-f358a560855f/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# 5 Data Similarity Metrics\nUnderstanding similarity metrics in data analysis and machine learning: A comprehensive guide\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nDecember 27, 20227 min read\n![Two similar faces next to each other \\(data similarity concept\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Data-similarity.jpg)\nPhoto by Alexander Grey on Unsplash \n_Preface: This article presents a summary of information about the given topic. It should not be considered original research. The information and code included in this article may be influenced by things I have read or seen in the past from various online articles, research papers, books, and open-source code._\n## Introduction\nSimilarity metrics are a vital tool in many data analysis and machine learning tasks, allowing us to compare and evaluate the similarity between different pieces of data. Many different metrics are available, each with pros and cons and suitable for different data types and tasks.\nThis article will explore some of the most common similarity metrics and compare their strengths and weaknesses. By understanding the characteristics and limitations of these metrics, we can choose the most appropriate one for our specific needs and ensure the accuracy and relevance of our results.\n## Euclidean distance\nThis metric calculates the straight-line distance between two points in n-dimensional space. It is often used for continuous numerical data and is easy to understand and implement. However, it can be sensitive to outliers and does not account for the relative importance of different features.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\npython\n\n```\nfrom scipy.spatial import distance\n\n# Calculate Euclidean distance between two points\npoint1 = [1, 2, 3]\npoint2 = [4, 5, 6]\n\n# Use the euclidean function from scipy's distance module to calculate the Euclidean distance\neuclidean_distance = distance.euclidean(point1, point2)\n```\n\n## Manhattan distance\nThis metric calculates the distance between two points by considering the absolute differences of their coordinates in each dimension and summing them. It is less sensitive to outliers than Euclidean distance, but it may not accurately reflect the actual distance between points in some cases.\npython\n\n```\nfrom scipy.spatial import distance\n\n# Calculate Manhattan distance between two points\npoint1 = [1, 2, 3]\npoint2 = [4, 5, 6]\n\n# Use the cityblock function from scipy's distance module to calculate the Manhattan distance\nmanhattan_distance = distance.cityblock(point1, point2)\n\n# Print the result\nprint(\"Manhattan Distance between the given two points: \" + \\\n      str(manhattan_distance))\n```\n\n## Cosine similarity\nThis metric calculates the similarity between two vectors by considering their angle. It is often used for text data and is resistant to changes in the magnitude of the vectors. However, it does not consider the relative importance of different features.\npython\n\n```\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# Calculate cosine similarity between two vectors\nvector1 = [1, 2, 3]\nvector2 = [4, 5, 6]\n\n# Use the cosine_similarity function from scikit-learn to calculate the similarity\ncosine_sim = cosine_similarity([vector1], [vector2])[0][0]\n\n# Print the result\nprint(\"Cosine Similarity between the given two vectors: \" + \\\n      str(cosine_sim))\n```\n\n## Jaccard similarity\nThis metric calculates the similarity between two sets by considering the size of their intersection and union. It is often used for categorical data and is resistant to changes in the size of the sets. However, it does not consider the sets' order or frequency of elements.\npython\n\n```\ndef jaccard_similarity(list1, list2):\n    \"\"\"\n    Calculates the Jaccard similarity between two lists.\n    \n    Parameters:\n    list1 (list): The first list to compare.\n    list2 (list): The second list to compare.\n    \n    Returns:\n    float: The Jaccard similarity between the two lists.\n    \"\"\"\n    # Convert the lists to sets for easier comparison\n    s1 = set(list1)\n    s2 = set(list2)\n    \n    # Calculate the Jaccard similarity by taking the length of the intersection of the sets\n    # and dividing it by the length of the union of the sets\n    return float(len(s1.intersection(s2)) / len(s1.union(s2)))\n\n# Calculate Jaccard similarity between two sets\nset1 = [1, 2, 3]\nset2 = [2, 3, 4]\njaccard_sim = jaccard_similarity(set1, set2)\n\n# Print the result\nprint(\"Jaccard Similarity between the given two sets: \" + \\\n      str(jaccard_sim))\n```\n\n## Pearson correlation coefficient\nThis metric calculates the linear correlation between two variables. It is often used for continuous numerical data and considers the relative importance of different features. However, it may not accurately reflect non-linear relationships.\npython\n\n```\nimport numpy as np\n\n# Calculate Pearson correlation coefficient between two variables\nx = [1, 2, 3, 4]\ny = [2, 3, 4, 5]\n\n# Numpy corrcoef function to calculate the Pearson correlation coefficient and p-value\npearson_corr = np.corrcoef(x, y)[0][1]\n\n# Print the result\nprint(\"Pearson Correlation between the given two variables: \" + \\\n      str(pearson_corr))\n```\n\nNow that we have reviewed the basics of these distance metrics, let’s consider a practical scenario and apply them to compare the results.\n## Scenario\nSuppose we have 5 items with numerical attributes and we want to compare the similarities between these products in order to facilitate applications such as clustering, classification, or perhaps, recommendations.\nThe following code computes the similarity metrics for the given products and their attributes using various distance metrics and then plots the results in a heat map for evaluation.\npython\n\n```\nimport numpy as np\nimport seaborn as sns\nimport random\nimport matplotlib.pyplot as plt\nimport pprint\n\ndef calculate_similarities(products):\n    \"\"\"Calculate the similarity measures between all pairs of products.\n    \n    Parameters\n    ----------\n    products : list\n        A list of dictionaries containing the attributes of the products.\n    \n    Returns\n    -------\n    euclidean_similarities : numpy array\n        An array containing the Euclidean distance between each pair of products.\n    manhattan_distances : numpy array\n        An array containing the Manhattan distance between each pair of products.\n    cosine_similarities : numpy array\n        An array containing the cosine similarity between each pair of products.\n    jaccard_similarities : numpy array\n        An array containing the Jaccard index between each pair of products.\n    pearson_similarities : numpy array\n        An array containing the Pearson correlation coefficient between each pair of products.\n    \"\"\"\n    # Initialize arrays to store the similarity measures\n    euclidean_similarities = np.zeros((len(products), len(products)))\n    manhattan_distances = np.zeros((len(products), len(products)))\n    cosine_similarities = np.zeros((len(products), len(products)))\n    jaccard_similarities = np.zeros((len(products), len(products)))\n    pearson_similarities = np.zeros((len(products), len(products)))\n\n    # Calculate all the similarity measures in a single loop\n    for i in range(len(products)):\n        for j in range(i+1, len(products)):\n            p1 = products[i]['attributes']\n            p2 = products[j]['attributes']\n\n            # Calculate Euclidean distance\n            euclidean_similarities[i][j] = distance.euclidean(p1, p2)\n            euclidean_similarities[j][i] = euclidean_similarities[i][j]\n\n            # Calculate Manhattan distance\n            manhattan_distances[i][j] = distance.cityblock(p1, p2)\n            manhattan_distances[j][i] = manhattan_distances[i][j]\n\n            # Calculate cosine similarity\n            cosine_similarities[i][j] = cosine_similarity([p1], [p2])[0][0]\n            cosine_similarities[j][i] = cosine_similarities[i][j]\n\n            # Calculate Jaccard index\n            jaccard_similarities[i][j] = jaccard_similarity(p1, p2)\n            jaccard_similarities[j][i] = jaccard_similarities[i][j]\n\n            # Calculate Pearson correlation coefficient\n            pearson_similarities[i][j] = np.corrcoef(p1, p2)[0][1]\n            pearson_similarities[j][i] = pearson_similarities[i][j]\n            \n    return euclidean_similarities, manhattan_distances, cosine_similarities, jaccard_similarities, pearson_similarities\n\ndef plot_similarities(similarities_list, labels, titles):\n    \"\"\"Plot the given similarities as heatmaps in subplots.\n    \n    Parameters\n    ----------\n    similarities_list : list of numpy arrays\n        A list of arrays containing the similarities between the products.\n    labels : list\n        A list of strings containing the labels for the products.\n    titles : list\n        A list of strings containing the titles for each plot.\n    \n    Returns\n    -------\n    None\n        This function does not return any values. It only plots the heatmaps.\n    \"\"\"\n    # Set up the plot\n    fig, ax = plt.subplots(nrows=1, \n                           ncols=len(similarities_list), figsize=(6*len(similarities_list), 6/1.680))\n\n    for i, similarities in enumerate(similarities_list):\n        # Plot the heatmap\n        sns.heatmap(similarities, xticklabels=labels, yticklabels=labels, ax=ax[i])\n        ax[i].set_title(titles[i])\n        ax[i].set_xlabel(\"Product\")\n        ax[i].set_ylabel(\"Product\")\n    \n    # Show the plot\n    plt.show()\n\n# Define the products and their attributes\nproducts = [\n    {'name': 'Product 1', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 2', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 3', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 4', 'attributes': random.sample(range(1, 11), 5)},\n    {'name': 'Product 5', 'attributes': random.sample(range(1, 11), 5)}\n]\n\npprint.pprint(products)\n\neuclidean_similarities, manhattan_distances, \\\ncosine_similarities, jaccard_similarities, \\\npearson_similarities = calculate_similarities(products)\n\n# Set the labels for the x-axis and y-axis\nproduct_labels = [product['name'] for product in products]\n\n# List of similarity measures and their titles\nsimilarities_list = [euclidean_similarities, cosine_similarities, pearson_similarities, \n                     jaccard_similarities, manhattan_distances]\ntitles = [\"Euclidean Distance\", \"Cosine Similarity\", \"Pearson Correlation Coefficient\", \n          \"Jaccard Index\", \"Manhattan Distance\"]\n\n# Plot the heatmaps\nplot_similarities(similarities_list, product_labels, titles)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/data-similarity-1-1024x178.png)\nAs we can see from the charts, each similarity metric produces a heat map that represents different similarities between the products, and on a different scale. While each similarity metric can be used to interpret whether two products are similar or not based on the metric’s value, it is difficult to determine a true measure of similarity when comparing the results across different distance metrics.\n### How to choose the correct **metric**\nThere is no single “true” answer when it comes to choosing a similarity metric, as different metrics are better suited for different types of data and different analysis goals. However, there are some factors that can help narrow down the possible metrics that might be appropriate for a given situation. Some things to consider when choosing a similarity metric include:\n  * **The type of data** : Some metrics are more appropriate for continuous data, while others are better suited for categorical or binary data.\n  * **The characteristics of the data** : Different metrics are sensitive to different aspects of the data, such as the magnitudes of differences between attributes or the angles between attributes. Consider which characteristics of the data are most important to your analysis and choose a similarity metric that is sensitive to these characteristics.\n  * **The goals of your analysis** : Different metrics can highlight different patterns or relationships in the data, so consider what you are trying to learn from your analysis and choose a distance metric that is well-suited to this purpose.\n\n\nPersonally, I often use the following chart as a starting point when choosing a similarity metric.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/data-similarity-2.png)\nAgain, it is important to carefully consider the data type and characteristics when selecting a similarity metric, as well as the specific goals of the analysis.\nAll of the code used in this article can be found at [Jupyter Notebook](https://github.com/kapadias/medium-articles/blob/master/general-data-science/similarities-measures/similarity-measures.ipynb).\n_Thanks for reading. If you have any feedback, please feel to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (shmkapadia[at]gmail[dot]com)_.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Distance Metrics](https://towardsdatascience.com/tag/distance-metrics/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Similarity Metrics](https://towardsdatascience.com/tag/similarity-metrics/)[Statistics](https://towardsdatascience.com/tag/statistics/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&title=5%20Data%20Similarity%20Metrics)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&title=5%20Data%20Similarity%20Metrics)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2F5-data-similarity-metrics-f358a560855f%2F&text=5%20Data%20Similarity%20Metrics)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/0bNndevisK72zgVF_.jpg)](https://towardsdatascience.com/solving-a-tennis-refactoring-challenge-in-python-using-solid-f1282f85e7e0/)\n## [Solving a Tennis Refactoring Challenge in Python using SOLID](https://towardsdatascience.com/solving-a-tennis-refactoring-challenge-in-python-using-solid-f1282f85e7e0/)\n[Software Engineering](https://towardsdatascience.com/category/programming/software-engineering/)\nA step-by-step illustration of how to use SOLID to solve a refactoring challenge\n[Tomer Gabay](https://towardsdatascience.com/author/tomergabay/)\nFebruary 5, 20249 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1mYCCALrKk6cgv1lkr4FFyA.png)](https://towardsdatascience.com/techniques-for-dimensionality-reduction-927a10135356/)\n## [Techniques for Dimensionality Reduction](https://towardsdatascience.com/techniques-for-dimensionality-reduction-927a10135356/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA guide for employing dimensionality reduction to improve an AI model's efficacy\n[Matthew Connelly](https://towardsdatascience.com/author/matthewconnelly/)\nJune 13, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/12/cardiff.jpg)](https://towardsdatascience.com/geospatial-exploratory-data-analysis-with-geopandas-and-duckdb/)\n## [Geospatial exploratory data analysis with GeoPandas and DuckDB](https://towardsdatascience.com/geospatial-exploratory-data-analysis-with-geopandas-and-duckdb/)\n[Programming](https://towardsdatascience.com/category/programming/)\nWhich UK city has the safest drivers?\n[Thomas Reid](https://towardsdatascience.com/author/thomas_reid/)\nDecember 15, 202513 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/0BrLBf7ORwzRWkv-k-scaled.jpg)](https://towardsdatascience.com/conditional-probabilities-seattle-rain-and-tricky-friends-aa1f33c20e29/)\n## [Conditional Probabilities, Seattle Rain, And Tricky Friends](https://towardsdatascience.com/conditional-probabilities-seattle-rain-and-tricky-friends-aa1f33c20e29/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nBetter Understand Probability By Tackling This Data Science Interview Question (With Python)\n[Tony Yiu](https://towardsdatascience.com/author/tonester524/)\nMay 31, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/0IQFs98-bIbzpc8jc.jpg)](https://towardsdatascience.com/analysis-of-variance-anova-8dc889d2fc3a/)\n## [Analysis of Variance - ANOVA](https://towardsdatascience.com/analysis-of-variance-anova-8dc889d2fc3a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nCollege Statistics with Python\n[Luís Roque](https://towardsdatascience.com/author/luisroque/)\nAugust 3, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/11/1x0wT1SUjJnwyfZDdnfqkwQ-scaled.jpeg)](https://towardsdatascience.com/writing-llms-in-rust-looking-for-an-efficient-matrix-multiplication-e9539b0cb9d3/)\n## [Writing LLMs in Rust: Looking for an Efficient Matrix Multiplication](https://towardsdatascience.com/writing-llms-in-rust-looking-for-an-efficient-matrix-multiplication-e9539b0cb9d3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHere are the lessons I learned and how I am writing llm.rust and tackling the matrix multiplication problem\n[Stefano Bosisio](https://towardsdatascience.com/author/stefanobosisio1/)\nNovember 14, 202415 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1GQUonV5-GthZ_HiSw7NEpQ.png)](https://towardsdatascience.com/how-to-chunk-text-data-a-comparative-analysis-3858c4a0997a/)\n## [How to Chunk Text Data - A Comparative Analysis](https://towardsdatascience.com/how-to-chunk-text-data-a-comparative-analysis-3858c4a0997a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExploring and comparing distinct approaches to text chunking.\n[Solano Todeschini](https://towardsdatascience.com/author/solano-todeschini/)\nJuly 20, 202318 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/09DzhpFOZ_lxKGW42.jpg)](https://towardsdatascience.com/keeping-up-data-appearances-e5225d7620b0/)\n## [Keeping up (data) appearances](https://towardsdatascience.com/keeping-up-data-appearances-e5225d7620b0/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nData is the fuel to creating value for your customers and its application is far...\n[Chanade Hemming](https://towardsdatascience.com/author/chanadehemming/)\nMay 19, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/0204gvY4y_NVT-Kd4.jpeg)](https://towardsdatascience.com/fine-tune-llama-3-1-ultra-efficiently-with-unsloth-7196c7165bab/)\n## [Fine-Tune Llama 3.1 Ultra-Efficiently with Unsloth](https://towardsdatascience.com/fine-tune-llama-3-1-ultra-efficiently-with-unsloth-7196c7165bab/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nA beginner's guide to state-of-the-art supervised fine-tuning\n[Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\nJuly 29, 202412 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/6541e4c5eaf0/pages/",
  "body_markdown_path": "attachments/6541e4c5eaf0/pages/archived-body.md",
  "local_html": "attachments/6541e4c5eaf0/pages/archived-body.html",
  "body_source": "prior_capture"
}