ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

机器学习入门:基于鸢尾花数据集的分类实践

机器学习入门:基于鸢尾花数据集的分类实践 1. 项目概述鸢尾花分类的机器学习实践第一次接触机器学习时我选择了经典的鸢尾花分类作为入门项目。这个看似简单的任务实际上包含了机器学习工作流的完整闭环——从数据加载、特征分析到模型训练与评估。使用Python的scikit-learn库简称sklearn我们能在30行代码内实现一个准确率超过95%的分类器这对初学者建立信心尤为重要。鸢尾花数据集包含三个品种山鸢尾、变色鸢尾和维吉尼亚鸢尾各50条样本每条样本有四个特征萼片长度、萼片宽度、花瓣长度和花瓣宽度。这个数据集之所以成为机器学习界的Hello World是因为它兼具以下特点特征维度适中4维适合可视化分析样本量小150条但类别分布均衡特征与标签间存在明显可学习的关联性提示初学者常犯的错误是直接跳入模型训练。实际上花时间理解数据特性往往能事半功倍。2. 环境准备与数据探索2.1 基础环境配置推荐使用Anaconda创建Python 3.8环境主要依赖库包括pip install numpy pandas matplotlib scikit-learn验证sklearn版本本文基于1.0.2import sklearn print(sklearn.__version__)2.2 数据加载与初探sklearn内置了鸢尾花数据集加载方式如下from sklearn.datasets import load_iris iris load_iris() X iris.data # 特征矩阵 (150,4) y iris.target # 标签 (150,) feature_names iris.feature_names target_names iris.target_names通过pandas的DataFrame可以更直观地查看数据import pandas as pd df pd.DataFrame(X, columnsfeature_names) df[species] [target_names[i] for i in y] print(df.describe()) # 统计特征2.3 特征可视化分析使用seaborn的pairplot可以快速发现特征间的关系import seaborn as sns sns.pairplot(df, huespecies, palettehusl) plt.show()从散点矩阵图中可以观察到花瓣长度和宽度对分类最具判别力山鸢尾与其他两类在特征空间中有明显区隔变色鸢尾和维吉尼亚鸢尾存在部分重叠区域3. 模型训练与评估3.1 数据预处理虽然鸢尾花数据集已经过清洗但仍需进行标准拆分from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test train_test_split( X, y, test_size0.2, random_state42, stratifyy)注意stratify参数确保训练集和测试集的类别比例与原数据一致3.2 模型选择与训练我们比较三种经典算法3.2.1 K近邻KNNfrom sklearn.neighbors import KNeighborsClassifier knn KNeighborsClassifier(n_neighbors3) knn.fit(X_train, y_train)3.2.2 支持向量机SVMfrom sklearn.svm import SVC svm SVC(kernellinear, C1.0) svm.fit(X_train, y_train)3.2.3 决策树from sklearn.tree import DecisionTreeClassifier tree DecisionTreeClassifier(max_depth3) tree.fit(X_train, y_train)3.3 模型评估使用混淆矩阵和分类报告from sklearn.metrics import classification_report, confusion_matrix def evaluate(model, X_test, y_test): y_pred model.predict(X_test) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) print(KNN评估结果:) evaluate(knn, X_test, y_test)典型输出示例precision recall f1-score support 0 1.00 1.00 1.00 10 1 0.90 1.00 0.95 9 2 1.00 0.91 0.95 11 accuracy 0.97 30 macro avg 0.97 0.97 0.97 30 weighted avg 0.97 0.97 0.97 304. 关键问题与优化策略4.1 特征工程实践虽然原始特征表现良好但我们可以尝试特征缩放对SVM和KNN尤为重要from sklearn.preprocessing import StandardScaler scaler StandardScaler() X_train_scaled scaler.fit_transform(X_train) X_test_scaled scaler.transform(X_test)创建新特征如花瓣面积X_enhanced np.hstack([X, (X[:,2]*X[:,3]).reshape(-1,1)])4.2 超参数调优以KNN为例使用网格搜索寻找最佳n_neighborsfrom sklearn.model_selection import GridSearchCV param_grid {n_neighbors: range(1, 15)} grid GridSearchCV(KNeighborsClassifier(), param_grid, cv5) grid.fit(X_train_scaled, y_train) print(f最佳参数{grid.best_params_})4.3 模型解释性决策树的可视化特别有教学价值from sklearn.tree import plot_tree plt.figure(figsize(12,8)) plot_tree(tree, feature_namesfeature_names, class_namestarget_names, filledTrue) plt.show()5. 项目扩展与进阶方向5.1 模型部署使用joblib保存训练好的模型from joblib import dump dump(svm, iris_svm.joblib) # 加载使用 loaded_model load(iris_svm.joblib) sample [[5.1, 3.5, 1.4, 0.2]] print(target_names[loaded_model.predict(sample)[0]])5.2 跨语言应用通过ONNX实现模型跨平台部署from skl2onnx import convert_sklearn from skl2onnx.common.data_types import FloatTensorType initial_type [(float_input, FloatTensorType([None, 4]))] onnx_model convert_sklearn(svm, initial_typesinitial_type) with open(iris_svm.onnx, wb) as f: f.write(onnx_model.SerializeToString())5.3 实际应用思考虽然鸢尾花分类是教学案例但其方法论适用于医疗诊断中的病症分类工业产品质量检测客户分群与精准营销我在实际项目中总结的经验数据质量决定模型上限花60%时间在数据探索和清洗上简单模型好特征往往优于复杂模型原始特征模型评估要结合业务场景准确率不是唯一指标
返回列表