首页 分享 对鸢尾花数据集使用随机森林分类模型,输出评价指标

对鸢尾花数据集使用随机森林分类模型,输出评价指标

来源:花匠小妙招 时间:2024-12-07 20:13

一、鸢尾花数据集     

        鸢尾花数据集是机器学习和数据挖掘中常用的数据集之一, 该数据集共包含150个样本,其中每个样本代表了一朵鸢尾花,分别属于三个不同的品种:Setosa、Versicolor 和 Virginica。 对于每个样本,都测量了四个特征: 萼片长度(Sepal Length)萼片宽度(Sepal Width)  花瓣长度(Petal Length) 花瓣宽度(Petal Width) 这些特征是以厘米为单位测量的。使用这些特征,任务是在新样本中准确地预测鸢尾花所属的品种。 鸢尾花数据集是一个经典的分类问题,被广泛用于机器学习中的训练和测试,同时也是许多分类算法的实用案例(本例使用随机森林进行分类对7种评价指标进行输出展示)。

二、分类模型的评价指标

分类问题的评价指标通常包括以下几种:

1. 准确率(Accuracy):分类正确的样本数占总样本数的比例。

2. 精确率(Precision):真正例(True Positive)占所有被预测为正例(Positive)的样本数的比例。

3. 召回率(Recall):真正例占所有真实为正例的样本数的比例。

4. F1 Score(F1得分):精确率和召回率的调和平均数。F1得分越高,代表综合评价表现越好。

5. 混淆矩阵(Confusion Matrix):展示真实类别和预测类别之间的对应情况,是评价分类模型的基础。

6. ROC曲线(ROC Curve):绘制真正例率(TPR)和假正例率(FPR)之间的关系图。通常用来衡量模型在不同阈值下的分类效果。

7. AUC(Area Under Curve):ROC曲线下方的面积值,接近1的模型性能更好。如果在0.5或附加是最坏的情况,相当于随机分类,没有意义。如果是非常接近于0,相当于正类和负类预测反了,只需把结果反过来分类效果也是好的。

        不同的指标适用于不同的情况,应该根据具体的分类问题选择对应的评价指标,并综合考虑多个指标综合评价模型性能。

三、代码实现

1代码

import seaborn as sns

from sklearn.datasets import load_iris

from sklearn.ensemble import RandomForestClassifier

import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, roc_curve, auc

iris_dataset = load_iris()

iris_df = pd.DataFrame(data=iris_dataset.data, columns=iris_dataset.feature_names)

iris_df['species'] = iris_dataset.target_names[iris_dataset.target]

l = np.unique(iris_df['species'])

iris_df['species']=iris_df['species'].map({'setosa':0,'versicolor':1,'virginica':2})

X = iris_df.iloc[:, :-1].values

y = iris_df.iloc[:, -1].values.ravel()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

clf = RandomForestClassifier(n_estimators=100, random_state=42)

clf.fit(X_train, y_train)

y_pred = clf.predict(X_test)

y_score = clf.predict_proba(X_test)

print("Accuracy:", accuracy_score(y_test, y_pred))

print("Precision:", precision_score(y_test, y_pred, average='macro'))

print("Recall:", recall_score(y_test, y_pred, average='macro'))

print("F1 Score:", f1_score(y_test, y_pred, average='macro'))

print("Confusion Matrix:")

print(confusion_matrix(y_test, y_pred))

cm = confusion_matrix(y_test, y_pred)

cm = pd.DataFrame(cm, index=['setosa', 'versicolor', 'virginica'], columns=['setosa', 'versicolor', 'virginica'])

ax = sns.heatmap(cm, annot=True, cmap='Blues', cbar=False)

ax.set_xlabel('True Label')

ax.set_ylabel('Predicted Label')

plt.show()

fpr = dict()

tpr = dict()

roc_auc = dict()

n = len(l)

for i in range(n):

fpr[i], tpr[i], _ = roc_curve((y_test == i).astype('int'), y_score[:,i])

roc_auc[i] = auc(fpr[i], tpr[i])

plt.figure()

lw = 2

for i in range(n):

plt.plot(fpr[i], tpr[i], lw=lw,

label='ROC curve of class {0} (AUC = {1:0.2f})'.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], linestyle='--', lw=lw, color='k',

label='Luck')

plt.xlim([0.0, 1.0])

plt.ylim([0.0, 1.05])

plt.xlabel('False Positive Rate')

plt.ylabel('True Positive Rate')

plt.title('Receiver operating characteristic example')

plt.legend(loc="lower right")

plt.show()

print("AUC (area under ROC curve):")

for i in range(n):

print("tClass {}: {:0.2f}".format(i, roc_auc[i]))

2输出结果

Accuracy: 1.0

Precision: 1.0

Recall: 1.0

F1 Score: 1.0

Confusion Matrix:

[[19 0 0]

[ 0 13 0]

[ 0 0 13]]

AUC (area under ROC curve):

Class 0: 1.00

Class 1: 1.00

Class 2: 1.00

混淆矩阵热力图

ROC曲线

         可以看到模型分类效果各种指标的准确率都达到百分百,这里需要看看是不是存在过拟合,本例主要是对分类指标的展示,并未做过多处理。

相关知识

鸢尾花——随机森林分类模型(RandomForestClassifier)
使用鸢尾花数据集构建神经网络模型
【机器学习小实验5】基于决策树和随机森林的鸢尾花种类预测
python实践gcForest模型对鸢尾花数据集iris进行分类
实验一:鸢尾花数据集分类
第3章(下)基于Softmax回归完成鸢尾花分类任务
基于Logistic回归模型对鸢尾花数据集的线性多分类
python实战(一)——iris鸢尾花数据集分类
神经网络与深度学习(五)前馈神经网络(3)鸢尾花分类
分析鸢尾花数据集

网址: 对鸢尾花数据集使用随机森林分类模型,输出评价指标 https://www.huajiangbk.com/newsview950247.html

所属分类:花卉
上一篇: 聚类效果评估指标总结
下一篇: 培训效果评价总结(通用24篇)

推荐分享