11.28实验一:数据准备与模型评估

实验一:数据准备与模型评估

一、实验目的

熟悉 Python 的基本操作,掌握对数据集的读写实现、对模型性能的评估实现的能力;

加深对训练集、测试集、N 折交叉验证、模型评估标准的理解。

 

二、实验内容

1)利用 pandas 库从本地读取 iris 数据集;

2)从 scikit-learn 库中直接加载 iris 数据集;

3)实现五折交叉验证进行模型训练;

4)计算并输出模型的准确度、精度、召回率和 F1 值。

 

三、算法步骤、代码、及结果

   1. 算法伪代码

 

   数据集 = load_iris_dataset()

   数据集_df = 转换为DataFrame(数据集)

 

   标签_映射 = 创建标签映射表('Iris-setosa' -> 0, 'Iris-versicolor' -> 1, 'Iris-virginica' -> 2

   数据集_df['Species'] = 应用标签映射到数据集_df['Species']

   特征 = 提取特征列(数据集_df)

   标签 = 提取标签列(数据集_df['Species'])

 

   pca = 初始化PCA(n_components=2)

   降维数据 = pca.fit_transform(特征)

   (可选)可视化降维数据

   X_train, X_test, y_train, y_test = 划分数据集(特征, 标签, test_size=0.3, stratify=标签, random_state=2024)

   决策树 = 初始化DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=5, class_weight='balanced', random_state=2024)

   决策树.fit(X_train, y_train)

模型预测

    y_pred = 决策树.predict(X_test)

评估模型

   准确率 = 计算准确率(y_test, y_pred)

   精度 = 计算精度(y_test, y_pred, average='macro')

   召回率 = 计算召回率(y_test, y_pred, average='macro')

   F1分数 = 计算F1分数(y_test, y_pred, average='macro')

   输出准确率、精度、召回率和F1分数

 

   2. 算法主要代码

1)完整源代码

'''

Created on 20241118

 

@author: 席酒

'''

import pandas as pd

from sklearn.decomposition import PCA

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeClassifier

from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score

from sklearn.datasets import load_iris

 

# 加载iris数据集

iris = load_iris()

df = pd.DataFrame(data=iris.data, columns=iris.feature_names)

df['Species'] = iris.target

 

# 标签编码

label_index = {0: 'Iris-setosa', 1: 'Iris-versicolor', 2: 'Iris-virginica'}

df['Species_name'] = df['Species'].apply(lambda x: label_index[x])

label_map = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}

df['Species'] = df['Species_name'].apply(lambda x: label_map[x])

 

# 数据基本信息

print('数据量:', len(df))

print(df.head())

print('空值数量统计:')

print(df.isnull().sum())

print(df.describe())

 

# 删除不需要的列

df = df.drop(['Species_name'], axis=1)

 

# 特征和标签

X = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']].values

y = df['Species'].values

 

# PCA 降维

pca = PCA(n_components=2)

pca_data = pca.fit_transform(X)

 

# 可视化 PCA 结果

plt.scatter(pca_data[:, 0], pca_data[:, 1], c=y)

plt.title('PCA of Iris Dataset')

plt.xlabel('Principal Component 1')

plt.ylabel('Principal Component 2')

plt.colorbar(ticks=[0, 1, 2], label='Species')

plt.show()

 

# 划分训练集和测试集

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

print('训练集数据量:', len(X_train))

print('测试集数据量:', len(X_test))

 

# 决策树模型训练

dt = DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=5, class_weight='balanced', random_state=2024)

dt.fit(X_train, y_train)

 

# 预测

y_pred = dt.predict(X_test)

 

# 评估模型

accuracy = accuracy_score(y_test, y_pred)

print('Accuracy:', accuracy)

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

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

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

 

2)调用库方法

 

  1. 结果截图(包括:准确率;精度、召回率、F1

数据量: 150

sepal length (cm) sepal width (cm) ... Species Species_name

0 5.1 3.5 ... 0 Iris-setosa

1 4.9 3.0 ... 0 Iris-setosa

2 4.7 3.2 ... 0 Iris-setosa

3 4.6 3.1 ... 0 Iris-setosa

4 5.0 3.6 ... 0 Iris-setosa

 

[5 rows x 6 columns]

空值数量统计:

sepal length (cm) 0

sepal width (cm) 0

petal length (cm) 0

petal width (cm) 0

Species 0

Species_name 0

dtype: int64

sepal length (cm) sepal width (cm) ... petal width (cm) Species

count 150.000000 150.000000 ... 150.000000 150.000000

mean 5.843333 3.057333 ... 1.199333 1.000000

std 0.828066 0.435866 ... 0.762238 0.819232

min 4.300000 2.000000 ... 0.100000 0.000000

25% 5.100000 2.800000 ... 0.300000 0.000000

50% 5.800000 3.000000 ... 1.300000 1.000000

75% 6.400000 3.300000 ... 1.800000 2.000000

max 7.900000 4.400000 ... 2.500000 2.000000

 

[8 rows x 5 columns]

训练集数据量: 105

测试集数据量: 45

Accuracy: 0.9111111111111111

Precision: 0.9111111111111111

Recall: 0.9111111111111111

F1: 0.9111111111111111

 

posted @     阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示