分类的结果有的四个基本属性,其他各种属性都是在此基础上计算而来的。
# 鸢尾花数据集的特点
鸢尾花的特征有4个:
1. Sepal Length(花萼长度)
2. Sepal Width(花萼宽度)
3. Petal Length(花瓣长度)
4. Petal Width(花瓣宽度)
鸢尾花的种类有3种:
1. Iris Setosa(山鸢尾)
2. Iris Versicolour(杂色鸢尾)
3. Iris Virginica(维吉尼亚鸢尾)
| 预测为维吉尼亚鸢尾 | 预测为杂色鸢尾 | 预测为山鸢尾 | |
|---|---|---|---|
| 实际为维吉尼亚鸢尾 | 49 | 1 | 0 |
| 实际为杂色鸢尾 | 4 | 46 | 0 |
| 实际为山鸢尾 | 1 | 0 | 49 |
那么以维吉尼亚鸢尾为例
TP = 49
FP = 4+1 = 5
FN = 1+0 = 1
精确率(Precision)
召回率(Recall)
准确率(Accuracy)
F1分数(F1-score)是分类问题的一个衡量指标 。一些多分类问题的机器学习竞赛,常常将F1-score作为最终测评的方法。它是精确率和召回率的调和平均数,最大为1,最小为0。
Precision和Recall的关系


在P-R曲线中,横坐标是recall,纵坐标是precision。下图就是一个P-R曲线的例子:

在ROC曲线中

AUC 即ROC曲线下的面积。
ROC和AUC的用处
from sklearn.datasets import load_iris
from sklearn import tree, svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
import numpy as np
# 加载数据集
iris = load_iris()
X = iris.data # 特征
y = iris.target # 标签
n_samples, n_features = X.shape
# 清洗数据集
random_state = np.random.RandomState(0)
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] # 引入random
y = label_binarize(y, classes=[0, 1, 2]) # 标签二值化, 把yes和no转化为0和1
n_classes = y.shape[1]
# 分割数据集
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=33)
# 引入训练模型
# clf = tree.DecisionTreeClassifier() # 决策树
clf = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True)) # 线性分类svm
# 开始训练
# clf.fit(X_train,y_train)
y_score = clf.fit(X_train, y_train).decision_function(X_test)
# 预测
y_predict=clf.predict(X_test)
# 计算F1-Score值
from sklearn.metrics import classification_report
print(clf.score(X_test,y_test)) # 使用均方误差对其进行打分,输出精确度,输出结果为0.9111, 随机后0.3555
print(classification_report(y_predict,y_test)) # F1-Score
# 输出结果为(012 分别表示3个标签的值)
'''
precision recall f1-score support
0 0.64 0.88 0.74 8
1 0.13 0.29 0.18 7
2 0.37 0.70 0.48 10
micro avg 0.36 0.64 0.46 25
macro avg 0.38 0.62 0.47 25
weighted avg 0.39 0.64 0.48 25
samples avg 0.36 0.36 0.36 25
'''
# 计算fpr和tpr
from sklearn.metrics import roc_curve, auc
fpr = dict()
tpr = dict()
roc_auc = dict()
# 用一个分类器对应一个类别,每个分类器都把其他全部的类别作为相反类别看待。
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) # 取当前类这一列的实际标签和预测标签
roc_auc[i] = auc(fpr[i], tpr[i]) # 计算AUC面积
# 绘制ROC曲线
import matplotlib.pyplot as plt
plt.figure()
plt.title("ROC Curve")
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.plot(fpr[2], tpr[2], color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.legend(loc="lower right")
plt.show()
