the-honk/python/calculators/SRCC.py

33 lines
679 B
Python
Raw Permalink Normal View History

2024-10-09 17:02:29 +00:00
import numpy
2024-10-09 17:02:32 +00:00
from _helpers import listInput
2024-10-09 17:02:29 +00:00
def rank(x):
2024-10-09 17:02:32 +00:00
x = numpy.array(x)
return x.argsort().argsort()
2024-10-09 17:02:29 +00:00
def spearman(a, b):
if len(a) != len(b):
2024-10-09 17:02:32 +00:00
raise Exception('Both datasets must be the same length!')
2024-10-09 17:02:29 +00:00
n = len(a)
2024-10-09 17:02:32 +00:00
# calculate rankings
aranks = rank(a)
2024-10-09 17:02:29 +00:00
branks = rank(b)
# work out the difference between ranks
d = aranks - branks
2024-10-09 17:02:32 +00:00
d = numpy.sum(d ** 2)
2024-10-09 17:02:29 +00:00
# plug the values into the formula
2024-10-09 17:02:32 +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)
2024-10-09 17:02:29 +00:00
2024-10-09 17:02:32 +00:00
print()
print('List A:', a)
print('List B:', b)
print('SRCC:', res)