开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 8 天,鸢尾花数据集绘制P-R曲线的代码(主要体现其微互斥性)
2.利用鸢尾花绘制P-R曲线
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
import numpy as np
iris = datasets.load_iris()
# 鸢尾花数据导入
x = iris.data
#每一列代表了萼片或花瓣的长宽,一共4列,每一列代表某个被测量的鸢尾植物,iris.shape=(150,4)
y = iris.target
#target是一个数组,存储了data中每条记录属于哪一类鸢尾植物,所以数组的长度是150,所有不同值只有三个
random_state = np.random.RandomState(0)
#给定状态为0的随机数组
n_samples, n_features = x.shape
x = np.c_[x, random_state.randn(n_samples, 200 * n_features)]
#添加合并生成特征测试数据集
x_train, x_test, y_train, y_test = train_test_split(x[y < 2], y[y < 2],
test_size=0.25,
random_state=0)
#根据此模型训练简单数据分类器
classifier = svm.LinearSVC(random_state=0)#线性分类支持向量机
classifier.fit(x_train, y_train)
y_score = classifier.decision_function(x_test)
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
precision, recall, _ =precision_recall_curve(y_test, y_score)
plt.fill_between(recall, precision,color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.0])
plt.xlim([0.0, 1.0])
plt.plot(recall, precision)
plt.title("Precision-Recall")
plt.show()
效果:
P-R图直观的显示出学习器在样本上的查全率、查准率。在进行比较时,若一个休息区的P-R曲线被另一个学习器的曲线完全“包住”,则可断言后者的性能优于前者。为取得比较合理的判断依据,将采用“平衡点”(Break-Even Point,BEP)度量对比算法的泛华性能强弱。它是“查准率=查全率”时的取值。但BEP还是过于简化,更常用F1度量(all为样例总数):