the-honk/python/calculators/SRCC.py

33 lines
679 B
Python
Raw Permalink Normal View History

2021-06-23 19:02:32 +00:00
import numpy
2021-08-26 01:42:17 +00:00
from _helpers import listInput
2021-06-23 19:02:32 +00:00
def rank(x):
2021-08-26 01:42:17 +00:00
x = numpy.array(x)
return x.argsort().argsort()
2021-06-23 19:02:32 +00:00
def spearman(a, b):
if len(a) != len(b):
2021-08-26 01:42:17 +00:00
raise Exception('Both datasets must be the same length!')
2021-06-23 19:02:32 +00:00
n = len(a)
2021-08-26 01:42:17 +00:00
# calculate rankings
aranks = rank(a)
2021-06-23 19:02:32 +00:00
branks = rank(b)
# work out the difference between ranks
d = aranks - branks
2021-08-26 01:42:17 +00:00
d = numpy.sum(d ** 2)
2021-06-23 19:02:32 +00:00
# plug the values into the formula
2021-08-26 01:42:17 +00:00
return 1 - ((6 * d) / (n ** 3 - n))
a = listInput('Please input a list of numbers')
b = listInput('Please input a second list of numbers')
res = spearman(a, b)
2021-06-23 19:02:32 +00:00
2021-08-26 01:42:17 +00:00
print()
print('List A:', a)
print('List B:', b)
print('SRCC:', res)