本文基于以下链接:sklearn中文文档,sklearn官网
模型选择Interface
make_scorer
sklearn.metrics.make_scorer(score_func, *, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs)
构建一个计分器,用于模型进行参数选择
分类评估准则:Classification metrics
accuracy_score
sklearn.metrics.accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None)
分类准确性分数
在多分类中,该函数计算子集准确性:一个样本中预测的标签集必须与y中对应的标签集完全匹配。
参数
- y_true:1维 array,label indicator array(标签指示数组),sparse matrix(稀疏矩阵)
- y_pred:与上一样
y_true就是y_test,y_pred就是你的模型根据x_test预测出的结果 - normalize:bool,默认为True
- True时返回准确率,False为准确的个数
- sample_weight:array-like of shape(n_samples),默认为None
- 设置某些权重
note
在二分类和多分类中,这个方法相当于jaccard_score方法
示例
>>> from sklearn.metrics import accuracy_score
>>> y_pred = [0, 2, 1, 3]
>>> y_true = [0, 1, 2, 3]
>>> accuracy_score(y_true, y_pred)
0.5
>>> accuracy_score(y_true, y_pred, normalize=False)
2
auc
sklearn.metrics.auc(x, y)
官方链接
使用梯形法则计算AUC
示例
>>> import numpy as np
>>> from sklearn import metrics
>>> y = np.array([1, 1, 2, 2])
>>> pred = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)
>>> metrics.auc(fpr, tpr)
0.75
classification_report
sklearn.metrics.classification_report(y_true, y_pred, *, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division='warn')
构建文本报告,显示主要的分类度量
参数
- y_true,y_pred:这两个参数不再赘述
- labels:array,shape = [n_labels]
- sample_weight:array,其shape为n_samples,default = None
- 不为None时,表示设置sample的权重
- digits:int
- 只有out_dict为False时才有效,设置输出值的小数点位数
- out_dict:bool,default=False
- 若是True,将输出转为字典类型
- zero_division:‘warn’,0 or 1,默认为’warn’
- 设置值的返回。
示例
回归评估准则:Regression metrics
mean_absolute_error
sklearn.metrics.mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')
M A E ( y , y ^ ) = 1 n ∑ i = 1 n ∣ y i − y i ^ ∣ MAE(y,\hat{y}) = \frac{1}{n}\sum_{i=1}^{n}|y_i - \hat{y_i}| MAE(y,y^)=n1i=1∑n∣yi−yi^∣
示例
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> mean_absolute_error(y_true, y_pred)
0.75
#等价于以下
>>>y_true,y_pred = np.array(y_true),np.array(y_pred)
>>>np.sum(np.absolute(y_true-y_pred))/len(y_true)