How to Calculate Nonparametric Rank Correlation in Python
Correlation is a measure of the association between two variables.
It is easy to calculate and interpret when both variables have a well understood Gaussian distribution. When we do not know the distribution of the variables, we must use nonparametric rank correlation methods.
In this tutorial, you will discover rank correlation methods for quantifying the association between variables with a non-Gaussian distribution.
After completing this tutorial, you will know:
- How rank correlation methods work and the methods are that are available.
- How to calculate and interpret the Spearman’s rank correlation coefficient in Python.
- How to calculate and interpret the Kendall’s rank correlation coefficient in Python.
Let’s get started.
Tutorial Overview
This tutorial is divided into 4 parts; they are:
- Rank Correlation
- Test Dataset
- Spearman’s Rank Correlation
- Kendall’s Rank Correlation
Need help with Statistics for Machine Learning?
Take my free 7-day email crash course now (with sample code).
Click to sign-up and also get a free PDF Ebook version of the course.
Rank Correlation
Correlation refers to the association between the observed values of two variables.
The variables may have a positive association, meaning that as the values for one variable increase, so do the values of the other variable. The association may also be negative, meaning that as the values of one variable increase, the values of the others decrease. Finally, the association may be neutral, meaning that the variables are not associated.
Correlation quantifies this association, often as a measure between the values -1 to 1 for perfectly negatively correlated and perfectly positively correlated. The calculated correlation is referred to as the “correlation coefficient.” This correlation coefficient can then be interpreted to describe the measures.
See the table below to help with interpretation the correlation coefficient.
The correlation between two variables that each have a Gaussian distribution can be calculated using standard methods such as the Pearson’s correlation. This procedure cannot be used for data that does not have a Gaussian distribution. Instead, rank correlation methods must be used.
Rank correlation refers to methods that quantify the association between variables using the ordinal relationship between the values rather than the specific values. Ordinal data is data that has label values and has an order or rank relationship; for example: ‘low‘, ‘medium‘, and ‘high‘.
Rank correlation can be calculated for real-valued variables. This is done by first converting the values for each variable into rank data. This is where the values are ordered and assigned an integer rank value. Rank correlation coefficients can then be calculated in order to quantify the association between the two ranked variables.
Because no distribution for the values is assumed, rank correlation methods are referred to as distribution-free correlation or nonparametric correlation. Interestingly, rank correlation measures are often used as the basis for other statistical hypothesis tests, such as determining whether two samples were likely drawn from the same (or different) population distributions.
Rank correlation methods are often named after the researcher or researchers that developed the method. Four examples of rank correlation methods are as follows:
- Spearman’s Rank Correlation.
- Kendall’s Rank Correlation.
- Goodman and Kruskal’s Rank Correlation.
- Somers’ Rank Correlation.
In the following sections, we will take a closer look at two of the more common rank correlation methods: Spearman’s and Kendall’s.
Test Dataset
Before we demonstrate rank correlation methods, we must first define a test problem.
In this section, we will define a simple two-variable dataset where each variable is drawn from a uniform distribution (e.g. non-Gaussian) and the values of the second variable depend on the values of the first value.
Specifically, a sample of 1,000 random floating point values are drawn from a uniform distribution and scaled to the range 0 to 20. A second sample of 1,000 random floating point values are drawn from a uniform distribution between 0 and 10 and added to values in the first sample to create an association.
123 | # prepare datadata1=rand(1000)*20data2=data1+(rand(1000)*10) |
The complete example is listed below.
123456789101112 | # generate related variablesfrom numpy.random import randfrom numpy.random import seedfrom matplotlib import pyplot# seed random number generatorseed(1)# prepare datadata1=rand(1000)*20data2=data1+(rand(1000)*10)# plotpyplot.scatter(data1,data2)pyplot.show() |
Running the example generates the data sample and graphs the points on a scatter plot.
We can clearly see that each variable has a uniform distribution and the positive association between the variables is visible by the diagonal grouping of the points from the bottom left to the top right of the plot.
Spearman’s Rank Correlation
It may also be called Spearman’s correlation coefficient and is denoted by the lowercase greek letter rho (p). As such, it may be referred to as Spearman’s rho.
This statistical method quantifies the degree to which ranked variables are associated by a monotonic function, meaning an increasing or decreasing relationship. As a statistical hypothesis test, the method assumes that the samples are uncorrelated (fail to reject H0).
The Spearman rank-order correlation is a statistical procedure that is designed to measure the relationship between two variables on an ordinal scale of measurement.
The intuition for the Spearman’s rank correlation is that it calculates a Pearson’s correlation (e.g. a parametric measure of correlation) using the rank values instead of the real values. Where the Pearson’s correlation is the calculation of the covariance (or expected difference of observations from the mean) between the two variables normalized by the variance or spread of both variables.
Spearman’s rank correlation can be calculated in Python using the spearmanr() SciPy function.
The function takes two real-valued samples as arguments and returns both the correlation coefficient in the range between -1 and 1 and the p-value for interpreting the significance of the coefficient.
12 | # calculate spearman's correlationcoef,p=spearmanr(data1,data2) |
We can demonstrate the Spearman’s rank correlation on the test dataset. We know that there is a strong association between the variables in the dataset and we would expect the Spearman’s test to find this association.
The complete example is listed below.
123456789101112131415161718 | # calculate the spearman's correlation between two variablesfrom numpy.random import randfrom numpy.random import seedfrom scipy.stats import spearmanr# seed random number generatorseed(1)# prepare datadata1=rand(1000)*20data2=data1+(rand(1000)*10)# calculate spearman's correlationcoef,p=spearmanr(data1,data2)print('Spearmans correlation coefficient: %.3f'%coef)# interpret the significancealpha=0.05ifp>alpha:print('Samples are uncorrelated (fail to reject H0) p=%.3f'%p)else:print('Samples are correlated (reject H0) p=%.3f'%p) |
Running the example calculates the Spearman’s correlation coefficient between the two variables in the test dataset.
The statistical test reports a strong positive correlation with a value of 0.9. The p-value is close to zero, which means that the likelihood of observing the data given that the samples are uncorrelated is very unlikely (e.g. 95% confidence) and that we can reject the null hypothesis that the samples are uncorrelated.
12 | Spearmans correlation coefficient: 0.900Samples are correlated (reject H0) p=0.000 |
Kendall’s Rank Correlation
It is also called Kendall’s correlation coefficient, and the coefficient is often referred to by the lowercase Greek letter tau (t). In turn, the test may be called Kendall’s tau.
The intuition for the test is that it calculates a normalized score for the number of matching or concordant rankings between the two samples. As such, the test is also referred to as Kendall’s concordance test.
The Kendall’s rank correlation coefficient can be calculated in Python using the kendalltau() SciPy function. The test takes the two data samples as arguments and returns the correlation coefficient and the p-value. As a statistical hypothesis test, the method assumes (H0) that there is no association between the two samples.
12 | # calculate kendall's correlationcoef,p=kendalltau(data1,data2) |
We can demonstrate the calculation on the test dataset, where we do expect a significant positive association to be reported.
The complete example is listed below.
123456789101112131415161718 | # calculate the kendall's correlation between two variablesfrom numpy.random import randfrom numpy.random import seedfrom scipy.stats import kendalltau# seed random number generatorseed(1)# prepare datadata1=rand(1000)*20data2=data1+(rand(1000)*10)# calculate kendall's correlationcoef,p=kendalltau(data1,data2)print('Kendall correlation coefficient: %.3f'%coef)# interpret the significancealpha=0.05ifp>alpha:print('Samples are uncorrelated (fail to reject H0) p=%.3f'%p)else:print('Samples are correlated (reject H0) p=%.3f'%p) |
Running the example calculates the Kendall’s correlation coefficient as 0.7, which is highly correlated.
The p-value is close to zero (and printed as zero), as with the Spearman’s test, meaning that we can confidently reject the null hypothesis that the samples are uncorrelated.
12 | Kendall correlation coefficient: 0.709Samples are correlated (reject H0) p=0.000 |
Extensions
This section lists some ideas for extending the tutorial that you may wish to explore.
- List three examples where calculating a nonparametric correlation coefficient might be useful during a machine learning project.
- Update each example to calculate the correlation between uncorrelated data samples drawn from a non-Gaussian distribution.
- Load a standard machine learning dataset and calculate the pairwise nonparametric correlation between all variables.
If you explore any of these extensions, I’d love to know.
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Books
API
Articles
Summary
In this tutorial, you discovered rank correlation methods for quantifying the association between variables with a non-Gaussian distribution.
Specifically, you learned:
- How rank correlation methods work and the methods are that are available.
- How to calculate and interpret the Spearman’s rank correlation coefficient in Python.
- How to calculate and interpret the Kendall’s rank correlation coefficient in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Get a Handle on Statistics for Machine Learning!
Develop a working understanding of statistics
…by writing lines of code in python
It provides self-study tutorials on topics like:
Hypothesis Tests, Correlation, Nonparametric Stats, Resampling, and much more…
Discover how to Transform Data into Knowledge
Skip the Academics. Just Results.
相關推薦
How to Calculate Nonparametric Rank Correlation in Python
Tweet Share Share Google Plus Correlation is a measure of the association between two variables.
How to calculate MD5 check sum in Python
import sys import hashlib import md5 def getMd5(filePath): f = open(filePath, "rb") m = hashlib.md5() while True: da
[Python] How to unpack and pack collection in Python?
ide ont add off art video lec ref show It is a pity that i can not add the video here. As a result, i offer the link as below: How to
How to use *args and **kwargs in Python
這篇文章寫的滿好的耶,結論: 1星= array, 2星=dictionary. 1星範例: def test_var_args(farg, *args): print "formal arg:", farg for arg in args: print "an
Critical Values for Statistical Hypothesis Testing and How to Calculate Them in Python
Tweet Share Share Google Plus In is common, if not standard, to interpret the results of statist
[Tensorflow] 統計模型的引數數量 How to calculate the amount of parameters in my model?
import logging logging.basicConfig(level=logging.INFO, format='%(message)s', filemode='w', filename=config.logger) def _params_usage(): total
How To View the HTML Source in Google Chrome
inner eve spi together member mes mnt line split Whether you are new to the web industry or a seasoned veteran, viewing the HTML source o
How to Find Processlist Thread id in gdb !!!!!GDB 使用
ren openss lua comm lte ext htm out int https://mysqlentomologist.blogspot.jp/2017/07/ Saturday, July
How to Install The Latest Eclipse in Ubuntu 16.04, 15.10?
How to Install The Latest Eclipse in Ubuntu 16.04, 15.10? 1. Install Java Don’t have Java installed? Search for and install OpenJDK Java 7 or
How To Change Log Rate Limiting In Linux
ratelimit record cap reac systemctl evel rem mat mil By default in Linux there are a few different mechanisms in place that may rate limi
How to setup oAuth 1.0 in NetSuite RESTlet API 如何在NetSuite中設定RESTlet API的oAuth認證
步驟如下: 1. Got Restlet URL 訪問RESTlet的Deployment,這樣獲取WebService要Post或訪問到的具體URL地址, 如果你疑惑RESTlet是什麼,那要等我下一篇文章再介紹。 2. Setup Roles for Token user, goe
[轉]How to display the data read in DataReceived event handler of serialport
本文轉自:https://stackoverflow.com/questions/11590945/how-to-display-the-data-read-in-datareceived-event-handler-of-serialport 問: I have the followin
How to edit Vector attribute tables using Python/ArcPy?
Method 1: arcpy.UpdateCursor This should do it and is a little simpler than the examples in the online help for UpdateCursorwhich is ne
How to know the directory size in CENTOS 檢視資料夾大小
Under any linux system, you want to use the command du. (Disk Usage) Common usage is : du -sh file(s) name(s) or du -sh /path/to/dir/* du -sh
How to display count of notifications in app launcher icon
Android (“vanilla” android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .ap
How to get client Ip Address in Java Servlet
Try this one, String ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAdd
[iOS] How to make a Global function in Swift
You can create a custom class with the method you need like this: class MyScene: SKScene { func CheckMusicMute() { if InGameMusicOnOff == tr
Ask HN: How to take advantage of living in the Bay?
Before moving to the Bay, I had hoped that the Bay to America would be like America to the rest of the world.I grew up in a developing country with an auth
How to write tidy SQL queries in R
How to write tidy SQL queries in RMost of us have to interact with databases nowadays, and SQL is by far the most common language used. However, working wi
How to make the impossible possible in CSS with a little creativity
CSS Previous sibling selectors don’t exist, but that doesn’t mean we can’t use themIf you ever used CSS sibling selectors, you know there’s only two. The +