Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
2108 views

Пример работы с порядковыми данными

Вычисление коэффициента Кендалла по формуле

rК=2(PQ)n(n1).r^{\text{К}}=\frac{2(P-Q)}{n(n-1)}.
# Считываем данные из файла painters.csv f = open('painters.csv', 'r') data = [] for line in f : row = line[:-1].split(',') data.append(row) f.close() # Выделяем нужные признаки: Composition (столбец 2), Drawing (столбец 3) и убираем заголовок two_cols = [(int(row[1]), int(row[2])) for row in data[1:]] # Вычисляем величины n, P и Q n = len(two_cols) two_cols = sorted(two_cols, key=lambda x: x[0]) # сортируем по первому признаку P = 0 Q = 0 for i in range(n) : p = 0 q = 0 y_cur = two_cols[i][1] for x, y in two_cols[i+1:] : if y > y_cur : p = p + 1 if y < y_cur : q = q + 1 P = P + p Q = Q + q rK = 2*(P-Q)/(n*(n-1)) print 'Kendall coefficient:', float(rK) u_crit = 1.645 # находим по таблице u(1-0.1/2)=u(0.95) if abs(rK) > u_crit*sqrt(2*(2*n+5)/(9*n*(n-1))) : print 'Связь подтверждена' else : print 'Связи нет'
Kendall coefficient: 0.287910552061 Связь подтверждена

Использование встроенных функций Sage (via scipy.stats)

x = [int(row[0]) for row in two_cols[1:]] y = [int(row[1]) for row in two_cols[1:]] from scipy.stats import kendalltau result = kendalltau(x, y) print 'Kendall coefficient:', result[0] p_value = result[1] if p_value < 0.05 : print 'Связь подтверждена' else : print 'Связи нет'
Kendall coefficient: 0.377585149547 Связь подтверждена

Использование R

%r painters <- read.csv("painters.csv") composition <- painters$Composition drawing <- painters$Drawing cor.test(composition, drawing, method="kendall")
Kendall's rank correlation tau data: composition and drawing z = 3.3795, p-value = 0.0007261 alternative hypothesis: true tau is not equal to 0 sample estimates: tau 0.3447242