📚 The CoCalc Library - books, templates and other resources
License: OTHER
#contributed by Ben Hammer, 2013123def tied_rank(x):4"""5Computes the tied rank of elements in x.67This function computes the tied rank of elements in x.89Parameters10----------11x : list of numbers, numpy array1213Returns14-------15score : list of numbers16The tied rank f each element in x1718"""19sorted_x = sorted(zip(x,range(len(x))))20r = [0 for k in x]21cur_val = sorted_x[0][0]22last_rank = 023for i in range(len(sorted_x)):24if cur_val != sorted_x[i][0]:25cur_val = sorted_x[i][0]26for j in range(last_rank, i):27r[sorted_x[j][1]] = float(last_rank+1+i)/2.028last_rank = i29if i==len(sorted_x)-1:30for j in range(last_rank, i+1):31r[sorted_x[j][1]] = float(last_rank+i+2)/2.032return r3334def auc(actual, posterior):35"""36Computes the area under the receiver-operater characteristic (AUC)3738This function computes the AUC error metric for binary classification.3940Parameters41----------42actual : list of binary numbers, numpy array43The ground truth value44posterior : same type as actual45Defines a ranking on the binary numbers, from most likely to46be positive to least likely to be positive.4748Returns49-------50score : double51The mean squared error between actual and posterior5253"""54r = tied_rank(posterior)55num_positive = len([0 for x in actual if x==1])56num_negative = len(actual)-num_positive57sum_positive = sum([r[i] for i in range(len(r)) if actual[i]==1])58auc = ((sum_positive - num_positive*(num_positive+1)/2.0) /59(num_negative*num_positive))60return auc6162