在机器学习、数据挖掘领域,工业界往往会根据实际的业务场景拟定相应的业务指标。本文旨在一起学习比较经典的三大类评价指标,其中第一、二类主要用于分类场景、第三类主要用于回归预测场景,基本思路是从概念公式,到优缺点,再到具体应用(分类问题,本文以二分类为例)。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
x = np.linspace(0,1,100)
p,r = np.meshgrid(x,x) #meshgrid函数创建一个二维的坐标网络
z = 2*p*r/(p+r)
ax.plot_surface(x,y,z,rstride=4,cstride=4,cmap=cm.YlGnBu_r)
ax.set_title('F1') #标题
ax.set_xlabel('precision') #x轴标签
ax.set_ylabel('recall') #y轴标签
plt.show()
library(ROCR)
p=c(0.5,0.6,0.55,0.4,0.7)
y=c(1,1,0,0,1)
pred = prediction(p, y)
perf = performance(pred,"tpr","fpr")
plot(perf,col="blue",lty=3, lwd=3,cex.lab=1.5, cex.axis=2, cex.main=1.5,main="ROC plot")
from sklearn import metrics
def aucfun(act,pred):
fpr, tpr, thresholds = metrics.roc_curve(act, pred, pos_label=1)
return metrics.auc(fpr, tpr)
#生成训练数据
set.seed(1999)
x1 = rnorm(1000)
x2 = rnorm(1000)
z = 1 + 2*x1 + 3*x2
pr = 1/(1+exp(-z))
y = rbinom(1000,1,pr)
#使用logloss作为训练目标函数
df = data.frame(y=y,x1=x1,x2=x2)
glm.fit=glm( y~x1+x2,data=df,family="binomial")
#下面使用auc作为训练目标函数
library(ROCR)
CalAUC <- function(real,pred){
rocr.pred=prediction(pred,real)
rocr.perf=performance(rocr.pred,'auc')
as.numeric([email protected])
}
#初始值
beta0=c(1,1,1)
loss <- function(beta){
z=beta[1]+beta[2]*x1+beta[3]*x2
pred=1/(1+exp(-z))
-CalAUC(y,pred)
}
res=optim(beta0,loss,method = "Nelder-Mead",control = list(maxit = 100))
def mapeobj(preds,dtrain):
gaps = dtrain.get_label()
grad = np.sign(preds-gaps)/gaps
hess = 1/gaps
grad[(gaps==0)] = 0
hess[(gaps==0)] = 0
return grad,hess
def evalmape(preds, dtrain):
gaps = dtrain.get_label()
err = abs(gaps-preds)/gaps
err[(gaps==0)] = 0
err = np.mean(err)
return 'error',err
参考资源
1.关于AUC,你应该知道的和可能不知道的 (PS.最近才知道,这篇文章的作者是工大的校友啊)