import numpy as np
def auc_calculate(labels ,preds ,n_bins=100):
postive_len = sum(labels)
negative_len = len(labels) - postive_len
total_case = postive_len * negative_len
pos_histogram = [0 for _ in range(n_bins)]
neg_histogram = [0 for _ in range(n_bins)]
bin_width = 1.0 / n_bins
for i in range(len(labels)):
nth_bin = int(preds[i ] /bin_width)
if labels[i ]==1:
pos_histogram[nth_bin] += 1
else:
neg_histogram[nth_bin] += 1
accumulated_neg = 0
satisfied_pair = 0
for i in range(n_bins):
satisfied_pair += (pos_histogram[i ] *accumulated_neg + pos_histogram[i ] *neg_histogram[i ] *0.5)
accumulated_neg += neg_histogram[i]
return satisfied_pair / float(total_case)
if __name__ == '__main__':
while True:
num_length =input() # 用例个数
list_label =[]
list_pred =[]
for i in range(int(num_length)):
labelAndpred =input().split(' ') # 接收用例并分割
case =[float(labelAndpred[i]) for i in range(len(labelAndpred))] # float型list
list_label.append(case[::2]) # 取出label
list_pred.append(case[1::2]) # 取出pred
array_label =np.array(list_label)
array_pred =np.array(list_pred)
print(auc_calculate(array_label ,array_pred)) # 计算AUC输出
AUC计算
最新推荐文章于 2025-05-28 16:00:05 发布