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.2):

import 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, columns=feature_names)
df['species'] = [target_names[i] for i in y]
print(df.describe())  # 统计特征

2.3 特征可视化分析

使用seaborn的pairplot可以快速发现特征间的关系:

import seaborn as sns
sns.pairplot(df, hue='species', palette='husl')
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_size=0.2, random_state=42, stratify=y)

注意:stratify参数确保训练集和测试集的类别比例与原数据一致

3.2 模型选择与训练

我们比较三种经典算法:

3.2.1 K近邻(KNN)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
3.2.2 支持向量机(SVM)
from sklearn.svm import SVC
svm = SVC(kernel='linear', C=1.0)
svm.fit(X_train, y_train)
3.2.3 决策树
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=3)
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        30

4. 关键问题与优化策略

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_neighbors:

from sklearn.model_selection import GridSearchCV
param_grid = {'n_neighbors': range(1, 15)}
grid = GridSearchCV(KNeighborsClassifier(), param_grid, cv=5)
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_names=feature_names, 
          class_names=target_names, filled=True)
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_types=initial_type)
with open("iris_svm.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

5.3 实际应用思考

虽然鸢尾花分类是教学案例,但其方法论适用于:

  • 医疗诊断中的病症分类
  • 工业产品质量检测
  • 客户分群与精准营销

我在实际项目中总结的经验:

  1. 数据质量决定模型上限,花60%时间在数据探索和清洗上
  2. 简单模型+好特征往往优于复杂模型+原始特征
  3. 模型评估要结合业务场景,准确率不是唯一指标
Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐