数据集下载地址(一此常见的数据科学 Python 库,都集成了鸢尾花(iris)数据集)
https://github.com/jackgo2080/dataOpen/blob/main/iris.data
数据集详情
鸢尾花数据集共收集了三类鸢尾花,即Setosa鸢尾花、Versicolour鸢尾花和Virginica鸢尾花,每一类鸢尾花收集了50条样本记录,共计150条。
数据集包括4个属性,分别为花萼的长、花萼的宽、花瓣的长和花瓣的宽。对花瓣我们可能比较熟悉,花萼是什么呢?花萼是花冠外面的绿色被叶,在花尚未开放时,保护着花蕾。四个属性的单位都是cm,属于数值变量,四个属性均不存在缺失值的情况,字段如下:
sepal length(萼片长度)
sepal width(萼片宽度)
petal length(花瓣长度)
petal width (花瓣宽度)
Species(品种类别):分别是:Setosa、Versicolour、Virginica
单位都是厘米。
当然,以下是一个使用Python和scikit-learn库的机器学习模型编程示例,这个例子涵盖了数据预处理、模型选择、训练和评估的全过程。
假设我们正在处理一个分类问题,我们将使用著名的鸢尾花(Iris)数据集来演示这个过程。
1. 数据预处理
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
# 加载数据
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集分割为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 数据清洗:这里我们假设数据集已经比较干净,不需要额外处理
# 缺失值处理
imputer = SimpleImputer(strategy='mean') # 用均值填充缺失值
X_train = imputer.fit_transform(X_train)
X_test = imputer.transform(X_test)
# 特征选择:这里我们暂时使用所有特征,不进行特征选择
# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
2. 选择模型
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
# 决策树模型
dt = DecisionTreeClassifier(random_state=42)
# 随机森林模型
rf = RandomForestClassifier(random_state=42)
# 支持向量机模型
svm = SVC(random_state=42)
3. 训练模型
from sklearn.model_selection import GridSearchCV
# 决策树参数调优
param_grid_dt = {
'criterion': ['gini', 'entropy'],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10]
}
grid_search_dt = GridSearchCV(dt, param_grid_dt, cv=5)
grid_search_dt.fit(X_train, y_train)
# 选择最佳参数的决策树模型
best_dt = grid_search_dt.best_estimator_
4. 评估模型
from sklearn.metrics import accuracy_score, recall_score, f1_score, classification_report
# 使用测试集评估模型
y_pred_dt = best_dt.predict(X_test)
# 计算评估指标
accuracy = accuracy_score(y_test, y_pred_dt)
recall = recall_score(y_test, y_pred_dt