AUC Score 自定义实现二进制类仅使用 numpy 和 pandas

问题描述

虽然在没有 sklearn 的情况下实现 AUC 分数, 我正在获得 auc 分数。我在 numpy.trapz 中传递排序数组,但得到负值。 请在以下链接中找到数据文件http://www.filedropper.com/5a_1 请看下面的代码

import numpy as np
import pandas as pd

def pred_label(col,th):
  if(col<th):
    return 0
  else:
    return 1

def compute_tpr(tp,fp):
  return (tp/(tp+fp))

def compute_fpr(fp,tn):
  return (fp/(fp+tn))

def compute_auc_score(df,thresholds):
  auc_scores=[]
  tpr_array=[]
  fpr_array=[]
  for val in thresholds:
    y_predict=[]
    prob_value=df['proba']
    for value in prob_value:
      y_predict.append(pred_label(value,val))

    df['y_pred']=y_predict
    true_positive=0
    false_positive=0
    false_negative=0
    true_negative=0

    counter=[]
    counter=np.where((df['y']==1) & (df['y_pred']==1),1,0)  #11
    true_positive=np.count_nonzero(counter==1)

    counter=[]
    counter=np.where((df['y']==1) & (df['y_pred']==0),0)   #10
    false_negative=np.count_nonzero(counter==1)

    counter=[]
    counter=np.where((df['y']==0) & (df['y_pred']==0),0)   #00
    true_negative=np.count_nonzero(counter==1)

    counter=[]
    counter=np.where((df['y']==0) & (df['y_pred']==1),0)   #01
    false_positive=np.count_nonzero(counter==1)
    tpr_array.append(compute_tpr(true_positive,false_positive))
    fpr_array.append(compute_fpr(false_positive,true_negative))
    combo=zip(tpr_array,fpr_array)
    combo=sorted(combo)
    tpr_sorted=[x for x,y in combo]
    fpr_sorted=[y for x,y in combo]
  auc_scores.append(np.trapz(tpr_sorted,fpr_sorted))
  return auc_scores

#thresholds=[]
sorted_df=df.sort_values(by="proba")
thresholds=set(sorted_df['proba'])
auc_scores=[]
auc_scores=compute_auc_score(sorted_df,thresholds)
print(auc_scores)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)