scikit learn 分类预测实战教程 从数据准备到模型训练评估的完整流程详解

引言
scikit-learn 是 Python 中最流行的机器学习库之一,它提供了简单易用的 API 和丰富的算法实现,特别适合初学者和快速原型开发。在分类任务中,scikit-learn 能够帮助我们从原始数据开始,经过数据预处理、特征工程、模型训练、评估到最终的预测,形成一个完整的机器学习工作流。
本教程将通过一个完整的实战案例,详细讲解使用 scikit-learn 进行分类预测的每一个步骤。我们将使用经典的鸢尾花(Iris)数据集作为示例,这是一个多分类问题,非常适合演示分类任务的完整流程。通过本教程,你将掌握:
数据加载与探索性分析
数据预处理和特征工程
数据集划分
模型选择与训练
模型评估与调优
模型保存与部署
1. 环境准备
首先,确保你的 Python 环境中已经安装了必要的库。我们将使用以下库:
scikit-learn:核心机器学习库
pandas:数据处理和分析
numpy:数值计算
matplotlib 和 seaborn:数据可视化
你可以使用以下命令安装这些库:
pip install scikit-learn pandas numpy matplotlib seaborn
2. 数据加载与探索
2.1 加载数据集
scikit-learn 内置了许多经典数据集,包括鸢尾花数据集。我们可以通过
sklearn.datasets
模块加载它:
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np

# 加载鸢尾花数据集
iris = load_iris()

# 查看数据集的基本信息
print(“数据集特征名称:”, iris.feature_names)
print(“数据集目标名称:”, iris.target_names)
print(“数据集形状:”, iris.data.shape)
print(“目标值形状:”, iris.target.shape)
运行这段代码,你会看到类似以下输出:
数据集特征名称: [‘sepal length (cm)’, ‘sepal width (cm)’, ‘petal length (cm)’, ‘petal width (cm)’]
数据集目标名称: [‘setosa’, ‘versicolor’, ‘virginica’]
数据集形状: (150, 4)
目标值形状: (150,)
鸢尾花数据集包含 150 个样本,每个样本有 4 个特征(花萼长度、花萼宽度、花瓣长度、花瓣宽度),目标值是 3 种鸢尾花的类别(setosa、versicolor、virginica)。
2.2 转换为 DataFrame 便于分析
为了更方便地进行数据探索,我们可以将数据转换为 pandas DataFrame:
# 创建 DataFrame
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df[‘target’] = iris.target
df[‘species’] = df[‘target’].map({0: ‘setosa’, 1: ‘versicolor’, 2: ‘virginica’})

# 查看前5行数据
print(df.head())
输出结果:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target species
0 5.1 3.5 1.4 0.2 0 setosa
1 4.9 3.0 1.4 0.2 0 setosa
2 4.7 3.2 1.3 0.2 0 setosa
3 4.6 3.1 1.5 0.2 0 setosa
4 5.0 3.6 1.4 0.2 0 setosa
2.3 数据探索性分析
在建模之前,我们需要了解数据的分布情况、特征之间的关系以及类别分布:
import matplotlib.pyplot as plt
import seaborn as sns

# 设置绘图风格
plt.style.use(‘seaborn-v0_8′)
sns.set_palette(“husl”)

# 1. 查看类别分布
plt.figure(figsize=(8, 6))
sns.countplot(data=df, x=’species’)
plt.title(‘鸢尾花类别分布’)
plt.xlabel(‘类别’)
plt.ylabel(‘数量’)
plt.show()

# 2. 特征分布分析
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
features = iris.feature_names

for i, feature in enumerate(features):
row, col = i // 2, i % 2
sns.histplot(data=df, x=feature, hue=’species’, multiple=”stack”, ax=axes[row, col])
axes[row, col].set_title(f'{feature} 分布’)

plt.tight_layout()
plt.show()

# 3. 特征相关性热力图
plt.figure(figsize=(8, 6))
correlation_matrix = df[features].corr()
sns.heatmap(correlation_matrix, annot=True, cmap=’coolwarm’, center=0)
plt.title(‘特征相关性热力图’)
plt.show()

# 4. 箱线图查看特征分布
plt.figure(figsize=(12, 8))
for i, feature in enumerate(features):
plt.subplot(2, 2, i+1)
sns.boxplot(data=df, x=’species’, y=feature)
plt.title(f'{feature} 按类别分布’)
plt.tight_layout()
plt.show()
通过这些可视化分析,我们可以发现:
类别分布:鸢尾花数据集是平衡的,每个类别有 50 个样本
特征分布:setosa 类别的花瓣长度和宽度明显小于其他两个类别
相关性:花瓣长度和花瓣宽度之间有很强的正相关性
3. 数据预处理
3.1 缺失值处理
虽然鸢尾花数据集是完整的,但在实际项目中,我们经常需要处理缺失值。以下是常见的处理方法:
# 模拟缺失值处理
df_missing = df.copy()

# 随机添加一些缺失值
np.random.seed(42)
missing_indices = np.random.choice(df.index, size=10, replace=False)
df_missing.loc[missing_indices, ‘sepal length (cm)’] = np.nan

print(“缺失值统计:”)
print(df_missing.isnull().sum())

# 方法1:删除含有缺失值的行
df_drop = df_missing.dropna()
print(f”删除缺失值后剩余样本数: {len(df_drop)}”)

# 方法2:用均值填充
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy=’mean’)
df_filled = df_missing.copy()
df_filled[features] = imputer.fit_transform(df_missing[features])
print(“均值填充后缺失值统计:”, df_filled.isnull().sum().sum())
3.2 特征标准化/归一化
不同特征的量纲可能差异很大,标准化可以帮助模型更好地收敛:
from sklearn.preprocessing import StandardScaler, MinMaxScaler

# 分离特征和目标
X = df[features]
y = df[‘target’]

# 标准化(均值为0,方差为1)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 归一化(缩放到[0,1]范围)
minmax_scaler = MinMaxScaler()
X_normalized = minmax_scaler.fit_transform(X)

print(“标准化前特征范围:”)
print(f”最小值: {X.min().values}, 最大值: {X.max().values}”)
print(“\n标准化后特征范围:”)
print(f”最小值: {X_scaled.min(axis=0)}, 最大值: {X_scaled.max(axis=0)}”)
3.3 特征工程
虽然鸢尾花数据集的特征已经很直观,但在实际项目中,我们经常需要创建新特征:
# 创建新特征:花萼面积
df[‘sepal_area’] = df[‘sepal length (cm)’] * df[‘sepal width (cm)’]

# 创建新特征:花瓣面积
df[‘petal_area’] = df[‘petal length (cm)’] * df[‘petal width (cm)’]

# 创建新特征:花萼与花瓣面积比
df[‘area_ratio’] = df[‘sepal_area’] / df[‘petal_area’]

# 查看新特征
print(“添加新特征后的数据:”)
print(df[[‘sepal_area’, ‘petal_area’, ‘area_ratio’]].head())
4. 数据集划分
在机器学习中,我们需要将数据集划分为训练集和测试集,以便评估模型的泛化能力:
from sklearn.model_selection import train_test_split

# 使用原始特征
X = df[features]
y = df[‘target’]

# 划分数据集:70%训练,30%测试
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)

print(f”训练集大小: {X_train.shape[0]}”)
print(f”测试集大小: {X_test.shape[0]}”)
print(f”训练集类别分布: {np.bincount(y_train)}”)
print(f”测试集类别分布: {np.bincount(y_test)}”)

# 使用新特征
X_enhanced = df[features + [‘sepal_area’, ‘petal_area’, ‘area_ratio’]]
X_train_enhanced, X_test_enhanced, y_train_enhanced, y_test_enhanced = train_test_split(
X_enhanced, y, test_size=0.3, random_state=42, stratify=y
)
关键参数说明:
test_size=0.3
:测试集占30%
random_state=42
:随机种子,确保结果可复现
stratify=y
:按类别比例分层抽样,保证训练集和测试集的类别分布一致
5. 模型训练
5.1 选择分类模型
scikit-learn 提供了多种分类算法,我们介绍几种常用的:
5.1.1 逻辑回归(Logistic Regression)
from sklearn.linear_model import LogisticRegression

# 创建模型
lr_model = LogisticRegression(random_state=42, max_iter=200)

# 训练模型
lr_model.fit(X_train, y_train)

# 查看模型参数
print(“逻辑回归模型参数:”)
print(f”系数: {lr_model.coef_}”)
print(f”截距: {lr_model.intercept_}”)
5.1.2 决策树(Decision Tree)
from sklearn.tree import DecisionTreeClassifier

# 创建模型
dt_model = DecisionTreeClassifier(
max_depth=3, # 最大深度
min_samples_split=2, # 内部节点再划分所需最小样本数
random_state=42
)

# 训练模型
dt_model.fit(X_train, y_train)

# 可视化决策树
from sklearn.tree import plot_tree
plt.figure(figsize=(15, 10))
plot_tree(dt_model,
feature_names=features,
class_names=iris.target_names,
filled=True,
rounded=True)
plt.title(‘决策树可视化’)
plt.show()
5.1.3 随机森林(Random Forest)
from sklearn.ensemble import RandomForestClassifier

# 创建模型
rf_model = RandomForestClassifier(
n_estimators=100, # 树的数量
max_depth=None, # 最大深度
min_samples_split=2, # 分裂所需最小样本数
random_state=42,
n_jobs=-1 # 使用所有CPU核心
)

# 训练模型
rf_model.fit(X_train, y_train)

# 查看特征重要性
feature_importance = pd.DataFrame({
‘feature’: features,
‘importance’: rf_model.feature_importances_
}).sort_values(‘importance’, ascending=False)

print(“特征重要性排序:”)
print(feature_importance)
5.1.4 支持向量机(SVM)
from sklearn.svm import SVC

# 创建模型
svm_model = SVC(
kernel=’rbf’, # 核函数
C=1.0, # 正则化参数
gamma=’scale’, # 核系数
random_state=42,
probability=True # 启用概率预测
)

# 训练模型
svm_model.fit(X_train, y_train)
5.1.5 K近邻(K-Nearest Neighbors)
from sklearn.neighbors import KNeighborsClassifier

# 创建模型
knn_model = KNeighborsClassifier(
n_neighbors=5, # 邻居数量
weights=’uniform’, # 权重函数
algorithm=’auto’ # 算法
)

# 训练模型
knn_model.fit(X_train, y_train)
5.2 模型训练与预测
训练完成后,我们可以使用模型进行预测:
# 使用训练好的模型进行预测
y_pred_lr = lr_model.predict(X_test)
y_pred_dt = dt_model.predict(X_test)
y_pred_rf = rf_model.predict(X_test)
y_pred_svm = svm_model.predict(X_test)
y_pred_knn = knn_model.predict(X_test)

# 查看预测结果
print(“逻辑回归预测结果:”, y_pred_lr[:10])
print(“真实标签:”, y_test.values[:10])
6. 模型评估
6.1 基础评估指标
6.1.1 准确率(Accuracy)
from sklearn.metrics import accuracy_score

# 计算准确率
accuracy_lr = accuracy_score(y_test, y_pred_lr)
accuracy_dt = accuracy_score(y_test, y_pred_dt)
accuracy_rf = accuracy_score(y_test, y_pred_rf)
accuracy_svm = accuracy_score(y_test, y_pred_svm)
accuracy_knn = accuracy_score(y_test, y_pred_knn)

print(“各模型准确率:”)
print(f”逻辑回归: {accuracy_lr:.4f}”)
print(f”决策树: {accuracy_dt:.4f}”)
print(f”随机森林: {accuracy_rf:.4f}”)
print(f”SVM: {accuracy_svm:.4f}”)
print(f”KNN: {accuracy_knn:.4f}”)
6.1.2 混淆矩阵(Confusion Matrix)
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# 计算混淆矩阵
cm_lr = confusion_matrix(y_test, y_pred_lr)

# 可视化混淆矩阵
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# 逻辑回归混淆矩阵
ConfusionMatrixDisplay(cm_lr, display_labels=iris.target_names).plot(ax=axes[0], cmap=’Blues’)
axes[0].set_title(‘逻辑回归混淆矩阵’)

# 随机森林混淆矩阵
cm_rf = confusion_matrix(y_test, y_pred_rf)
ConfusionMatrixDisplay(cm_rf, display_labels=iris.target_names).plot(ax=axes[1], cmap=’Blues’)
axes[1].set_title(‘随机森林混淆矩阵’)

plt.tight_layout()
plt.show()
6.1.3 分类报告(Classification Report)
from sklearn.metrics import classification_report

# 生成分类报告
report_lr = classification_report(y_test, y_pred_lr, target_names=iris.target_names)
print(“逻辑回归分类报告:”)
print(report_lr)

report_rf = classification_report(y_test, y_pred_rf, target_names=iris.target_names)
print(“\n随机森林分类报告:”)
print(report_rf)
6.2 高级评估指标
6.2.1 ROC曲线和AUC(适用于二分类,多分类需要扩展)
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize

# 二分类示例:只考虑前两个类别
binary_mask = y_test < 2 X_test_binary = X_test[binary_mask] y_test_binary = y_test[binary_mask] # 训练二分类模型 lr_binary = LogisticRegression(random_state=42) lr_binary.fit(X_train[y_train < 2], y_train[y_train < 2]) # 预测概率 y_pred_proba = lr_binary.predict_proba(X_test_binary)[:, 1] # 计算ROC曲线 fpr, tpr, thresholds = roc_curve(y_test_binary, y_pred_proba) roc_auc = auc(fpr, tpr) # 绘制ROC曲线 plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve (Binary Classification)') plt.legend(loc="lower right") plt.show() 6.2.2 交叉验证(Cross-Validation) from sklearn.model_selection import cross_val_score, StratifiedKFold # 创建交叉验证分割器 cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # 对随机森林模型进行交叉验证 cv_scores = cross_val_score(rf_model, X, y, cv=cv, scoring='accuracy') print(f"交叉验证准确率: {cv_scores}") print(f"平均准确率: {cv_scores.mean():.4f} (+/- {cv_scores.std() * 2:.4f})") # 对多个模型进行交叉验证比较 models = { '逻辑回归': LogisticRegression(random_state=42, max_iter=200), '决策树': DecisionTreeClassifier(random_state=42, max_depth=3), '随机森林': RandomForestClassifier(n_estimators=100, random_state=42), 'SVM': SVC(kernel='rbf', random_state=42), 'KNN': KNeighborsClassifier(n_neighbors=5) } print("\n各模型交叉验证结果:") for name, model in models.items(): scores = cross_val_score(model, X, y, cv=cv, scoring='accuracy') print(f"{name}: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})") 6.3 模型性能可视化 # 比较不同模型的性能 model_names = ['逻辑回归', '决策树', '随机森林', 'SVM', 'KNN'] accuracies = [accuracy_lr, accuracy_dt, accuracy_rf, accuracy_svm, accuracy_knn] plt.figure(figsize=(10, 6)) bars = plt.bar(model_names, accuracies, color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']) plt.ylim(0.9, 1.0) plt.ylabel('准确率') plt.title('不同分类模型性能比较') plt.xticks(rotation=45) # 在柱子上显示数值 for bar, acc in zip(bars, accuracies): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.001, f'{acc:.4f}', ha='center', va='bottom') plt.tight_layout() plt.show() 7. 模型调优 7.1 网格搜索(Grid Search) from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 5, 10, 15], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } # 创建网格搜索 rf = RandomForestClassifier(random_state=42, n_jobs=-1) grid_search = GridSearchCV( rf, param_grid, cv=5, scoring='accuracy', n_jobs=-1, verbose=1 ) # 执行搜索 grid_search.fit(X_train, y_train) # 输出最佳参数 print("最佳参数:", grid_search.best_params_) print("最佳交叉验证分数:", grid_search.best_score_) # 使用最佳模型 best_rf = grid_search.best_estimator_ y_pred_best = best_rf.predict(X_test) print("测试集准确率:", accuracy_score(y_test, y_pred_best)) 7.2 随机搜索(Randomized Search) from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint # 定义参数分布 param_dist = { 'n_estimators': randint(50, 250), 'max_depth': randint(3, 20), 'min_samples_split': randint(2, 11), 'min_samples_leaf': randint(1, 5) } # 创建随机搜索 random_search = RandomizedSearchCV( rf, param_distributions=param_dist, n_iter=20, # 尝试20种组合 cv=5, scoring='accuracy', random_state=42, n_jobs=-1, verbose=1 ) # 执行搜索 random_search.fit(X_train, y_train) print("最佳参数:", random_search.best_params_) print("最佳分数:", random_search.best_score_) 7.3 早停法(Early Stopping) from sklearn.experimental import enable_halving_search_cv from sklearn.model_selection import HalvingGridSearchCV # 使用连续减半搜索(更高效的网格搜索) param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 5, 10], 'min_samples_split': [2, 5] } halving_search = HalvingGridSearchCV( rf, param_grid, factor=2, # 每轮淘汰一半 resource='n_samples', max_resources=10000, cv=5, scoring='accuracy', n_jobs=-1, random_state=42 ) halving_search.fit(X_train, y_train) print("最佳参数:", halving_search.best_params_) 8. 模型保存与部署 8.1 保存模型 import joblib import pickle # 方法1:使用 joblib(推荐用于 scikit-learn 模型) joblib.dump(best_rf, 'best_random_forest_model.pkl') # 方法2:使用 pickle with open('best_random_forest_model.pkl', 'wb') as f: pickle.dump(best_rf, f) # 保存标准化器等预处理对象 joblib.dump(scaler, 'scaler.pkl') 8.2 加载模型并进行预测 # 加载模型 loaded_model = joblib.load('best_random_forest_model.pkl') loaded_scaler = joblib.load('scaler.pkl') # 创建新数据(模拟实际应用) new_data = np.array([[5.1, 3.5, 1.4, 0.2]]) # 预处理 new_data_scaled = loaded_scaler.transform(new_data) # 预测 prediction = loaded_model.predict(new_data_scaled) prediction_proba = loaded_model.predict_proba(new_data_scaled) print(f"预测类别: {iris.target_names[prediction[0]]}") print(f"预测概率: {dict(zip(iris.target_names, prediction_proba[0]))}") 8.3 构建完整的预测管道 from sklearn.pipeline import Pipeline # 创建完整的处理管道 pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier(n_estimators=100, random_state=42)) ]) # 训练管道 pipeline.fit(X_train, y_train) # 评估管道 print("管道准确率:", pipeline.score(X_test, y_test)) # 保存整个管道 joblib.dump(pipeline, 'iris_classifier_pipeline.pkl') # 使用管道进行预测 loaded_pipeline = joblib.load('iris_classifier_pipeline.pkl') new_prediction = loaded_pipeline.predict(new_data) print("管道预测结果:", iris.target_names[new_prediction[0]]) 9. 实战案例:完整工作流整合 下面是一个完整的、可运行的示例,整合了所有步骤: import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.pipeline import Pipeline import joblib def complete_classification_workflow(): """ 完整的分类预测工作流 """ print("=" * 60) print("鸢尾花分类预测完整工作流") print("=" * 60) # 1. 数据加载 print("\n1. 数据加载...") iris = load_iris() X = iris.data y = iris.target print(f"数据集形状: {X.shape}") print(f"特征: {iris.feature_names}") print(f"类别: {iris.target_names}") # 2. 数据集划分 print("\n2. 数据集划分...") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) print(f"训练集: {X_train.shape[0]} 样本") print(f"测试集: {X_test.shape[0]} 样本") # 3. 创建并训练模型 print("\n3. 模型训练...") pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier( n_estimators=100, max_depth=5, random_state=42, n_jobs=-1 )) ]) pipeline.fit(X_train, y_train) print("模型训练完成!") # 4. 模型评估 print("\n4. 模型评估...") y_pred = pipeline.predict(X_test) print(f"\n测试集准确率: {accuracy_score(y_test, y_pred):.4f}") print("\n分类报告:") print(classification_report(y_test, y_pred, target_names=iris.target_names)) print("\n混淆矩阵:") cm = confusion_matrix(y_test, y_pred) print(cm) # 5. 交叉验证 print("\n5. 交叉验证...") cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) cv_scores = cross_val_score(pipeline, X, y, cv=cv, scoring='accuracy') print(f"交叉验证准确率: {cv_scores}") print(f"平均准确率: {cv_scores.mean():.4f} (+/- {cv_scores.std() * 2:.4f})") # 6. 特征重要性 print("\n6. 特征重要性...") rf_model = pipeline.named_steps['classifier'] importance_df = pd.DataFrame({ 'feature': iris.feature_names, 'importance': rf_model.feature_importances_ }).sort_values('importance', ascending=False) print(importance_df) # 7. 保存模型 print("\n7. 保存模型...") joblib.dump(pipeline, 'iris_classifier_final.pkl') print("模型已保存为 'iris_classifier_final.pkl'") # 8. 模拟预测 print("\n8. 模拟预测...") new_sample = np.array([[5.9, 3.0, 5.1, 1.8]]) # virginica 类别 prediction = pipeline.predict(new_sample) probability = pipeline.predict_proba(new_sample) print(f"输入特征: {new_sample[0]}") print(f"预测类别: {iris.target_names[prediction[0]]}") print(f"预测概率: {dict(zip(iris.target_names, probability[0]))}") print("\n" + "=" * 60) print("工作流执行完毕!") print("=" * 60) # 执行完整工作流 if __name__ == "__main__": complete_classification_workflow() 10. 常见问题与解决方案 10.1 数据不平衡问题 from sklearn.utils.class_weight import compute_class_weight # 计算类别权重 class_weights = compute_class_weight( class_weight='balanced', classes=np.unique(y_train), y=y_train ) print("类别权重:", dict(zip(np.unique(y_train), class_weights))) # 在模型中使用类别权重 weighted_rf = RandomForestClassifier( n_estimators=100, class_weight='balanced', # 或者传入自定义权重字典 random_state=42 ) 10.2 特征选择 from sklearn.feature_selection import SelectKBest, f_classif # 选择最重要的2个特征 selector = SelectKBest(score_func=f_classif, k=2) X_train_selected = selector.fit_transform(X_train, y_train) X_test_selected = selector.transform(X_test) print("选中的特征:", np.array(features)[selector.get_support()]) # 训练并评估 rf_selected = RandomForestClassifier(n_estimators=100, random_state=42) rf_selected.fit(X_train_selected, y_train) print("特征选择后准确率:", rf_selected.score(X_test_selected, y_test)) 10.3 处理类别特征 from sklearn.preprocessing import OneHotEncoder, LabelEncoder # 如果有类别特征 # 假设我们有一个新的类别特征 'color' # df['color'] = ['red', 'blue', 'green'] * 50 # 标签编码(适用于有序类别) label_encoder = LabelEncoder() # df['color_encoded'] = label_encoder.fit_transform(df['color']) # 独热编码(适用于无序类别) # encoder = OneHotEncoder(sparse=False) # color_encoded = encoder.fit_transform(df[['color']]) 11. 最佳实践建议 始终从简单模型开始 :先尝试逻辑回归等简单模型,建立基准 使用交叉验证 :避免过拟合,获得更可靠的性能估计 特征工程很重要 :好的特征比复杂的模型更重要 保存所有中间结果 :便于复现和调试 监控训练过程 :使用 verbose 参数查看训练进度 处理缺失值 :根据数据特点选择合适的填充策略 标准化/归一化 :特别是对于基于距离的算法(如KNN、SVM) 使用管道 :避免数据泄露,简化工作流 12. 总结 本教程详细介绍了使用 scikit-learn 进行分类预测的完整流程,从数据准备到模型部署。我们涵盖了: 数据加载和探索性分析 数据预处理(缺失值处理、标准化、特征工程) 数据集划分的最佳实践 多种分类模型的实现和比较 全面的模型评估方法 模型调优技术(网格搜索、随机搜索) 模型保存和部署 实战案例和最佳实践 通过掌握这些技能,你将能够独立完成大多数分类任务。记住,机器学习是一个迭代的过程,需要不断实验、评估和改进。建议你在自己的项目中实践这些技术,并根据具体问题调整方法。 附录:完整代码汇总 # 完整代码汇总(可直接运行) import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.pipeline import Pipeline import joblib # 设置随机种子 np.random.seed(42) # 1. 加载数据 iris = load_iris() X, y = iris.data, iris.target # 2. 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) # 3. 创建模型管道 models = { '逻辑回归': Pipeline([('scaler', StandardScaler()), ('clf', LogisticRegression(random_state=42, max_iter=200))]), '决策树': Pipeline([('scaler', StandardScaler()), ('clf', DecisionTreeClassifier(random_state=42, max_depth=3))]), '随机森林': Pipeline([('scaler', StandardScaler()), ('clf', RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1))]), 'SVM': Pipeline([('scaler', StandardScaler()), ('clf', SVC(kernel='rbf', random_state=42, probability=True))]), 'KNN': Pipeline([('scaler', StandardScaler()), ('clf', KNeighborsClassifier(n_neighbors=5))]) } # 4. 训练和评估 results = {} for name, model in models.items(): # 训练 model.fit(X_train, y_train) # 预测 y_pred = model.predict(X_test) # 评估 accuracy = accuracy_score(y_test, y_pred) results[name] = accuracy print(f"\n{name} - 准确率: {accuracy:.4f}") print(classification_report(y_test, y_pred, target_names=iris.target_names, digits=4)) # 5. 比较结果 print("\n" + "="*50) print("模型性能比较:") for name, acc in sorted(results.items(), key=lambda x: x[1], reverse=True): print(f"{name}: {acc:.4f}") # 6. 保存最佳模型 best_model_name = max(results, key=results.get) best_model = models[best_model_name] joblib.dump(best_model, f'best_{best_model_name}_model.pkl') print(f"\n最佳模型 '{best_model_name}' 已保存") # 7. 交叉验证 print("\n交叉验证结果:") cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) for name, model in models.items(): scores = cross_val_score(model, X, y, cv=cv, scoring='accuracy') print(f"{name}: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})") 这个完整的代码示例展示了如何系统地进行分类预测任务。你可以直接运行这段代码,或者根据自己的需求进行修改和扩展。 # scikit-learn 分类预测实战教程:从数据准备到模型训练评估的完整流程详解 引言 scikit-learn 是 Python 中最流行的机器学习库之一,它提供了简单易用的 API 和丰富的算法实现,特别适合初学者和快速原型开发。在分类任务中,scikit-learn 能够帮助我们从原始数据开始,经过数据预处理、特征工程、模型训练、评估到最终的预测,形成一个完整的机器学习工作流。 本教程将通过一个完整的实战案例,详细讲解使用 scikit-learn 进行分类预测的每一个步骤。我们将使用经典的鸢尾花(Iris)数据集作为示例,这是一个多分类问题,非常适合演示分类任务的完整流程。通过本教程,你将掌握: 数据加载与探索性分析 数据预处理和特征工程 数据集划分 模型选择与训练 模型评估与调优 模型保存与部署 1. 环境准备 首先,确保你的 Python 环境中已经安装了必要的库。我们将使用以下库: scikit-learn:核心机器学习库 pandas:数据处理和分析 numpy:数值计算 matplotlib 和 seaborn:数据可视化 你可以使用以下命令安装这些库: pip install scikit-learn pandas numpy matplotlib seaborn 2. 数据加载与探索 2.1 加载数据集 scikit-learn 内置了许多经典数据集,包括鸢尾花数据集。我们可以通过 sklearn.datasets 模块加载它: from sklearn.datasets import load_iris import pandas as pd import numpy as np # 加载鸢尾花数据集 iris = load_iris() # 查看数据集的基本信息 print("数据集特征名称:", iris.feature_names) print("数据集目标名称:", iris.target_names) print("数据集形状:", iris.data.shape) print("目标值形状:", iris.target.shape) 运行这段代码,你会看到类似以下输出: 数据集特征名称: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] 数据集目标名称: ['setosa', 'versicolor', 'virginica'] 数据集形状: (150, 4) 目标值形状: (150,) 鸢尾花数据集包含 150 个样本,每个样本有 4 个特征(花萼长度、花萼宽度、花瓣长度、花瓣宽度),目标值是 3 种鸢尾花的类别(setosa、versicolor、virginica)。 2.2 转换为 DataFrame 便于分析 为了更方便地进行数据探索,我们可以将数据转换为 pandas DataFrame: # 创建 DataFrame df = pd.DataFrame(data=iris.data, columns=iris.feature_names) df['target'] = iris.target df['species'] = df['target'].map({0: 'setosa', 1: 'versicolor', 2: 'virginica'}) # 查看前5行数据 print(df.head()) 输出结果: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target species 0 1.0 3.5 1.4 0.2 0 setosa 1 4.9 3.0 1.4 0.2 0 setosa 2 4.7 3.2 1.3 0.2 0 setosa 3 4.6 3.1 1.5 0.2 0 setosa 4 5.0 3.6 1.4 0.2 0 setosa 2.3 数据探索性分析 在建模之前,我们需要了解数据的分布情况、特征之间的关系以及类别分布: import matplotlib.pyplot as plt import seaborn as sns # 设置绘图风格 plt.style.use('seaborn-v0_8') sns.set_palette("husl") # 1. 查看类别分布 plt.figure(figsize=(8, 6)) sns.countplot(data=df, x='species') plt.title('鸢尾花类别分布') plt.xlabel('类别') plt.ylabel('数量') plt.show() # 2. 特征分布分析 fig, axes = plt.subplots(2, 2, figsize=(12, 10)) features = iris.feature_names for i, feature in enumerate(features): row, col = i // 2, i % 2 sns.histplot(data=df, x=feature, hue='species', multiple="stack", ax=axes[row, col]) axes[row, col].set_title(f'{feature} 分布') plt.tight_layout() plt.show() # 3. 特征相关性热力图 plt.figure(figsize=(8, 6)) correlation_matrix = df[features].corr() sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0) plt.title('特征相关性热力图') plt.show() # 4. 箱线图查看特征分布 plt.figure(figsize=(12, 8)) for i, feature in enumerate(features): plt.subplot(2, 2, i+1) sns.boxplot(data=df, x='species', y=feature) plt.title(f'{feature} 按类别分布') plt.tight_layout() plt.show() 通过这些可视化分析,我们可以发现: 类别分布:鸢尾花数据集是平衡的,每个类别有 50 个样本 特征分布:setosa 类别的花瓣长度和宽度明显小于其他两个类别 相关性:花瓣长度和花瓣宽度之间有很强的正相关性 3. 数据预处理 3.1 缺失值处理 虽然鸢尾花数据集是完整的,但在实际项目中,我们经常需要处理缺失值。以下是常见的处理方法: # 模拟缺失值处理 df_missing = df.copy() # 随机添加一些缺失值 np.random.seed(42) missing_indices = np.random.choice(df.index, size=10, replace=False) df_missing.loc[missing_indices, 'sepal length (cm)'] = np.nan print("缺失值统计:") print(df_missing.isnull().sum()) # 方法1:删除含有缺失值的行 df_drop = df_missing.dropna() print(f"删除缺失值后剩余样本数: {len(df_drop)}") # 方法2:用均值填充 from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy='mean') df_filled = df_missing.copy() df_filled[features] = imputer.fit_transform(df_missing[features]) print("均值填充后缺失值统计:", df_filled.isnull().sum().sum()) 3.2 特征标准化/归一化 不同特征的量纲可能差异很大,标准化可以帮助模型更好地收敛: from sklearn.preprocessing import StandardScaler, MinMaxScaler # 分离特征和目标 X = df[features] y = df['target'] # 标准化(均值为0,方差为1) scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 归一化(缩放到[0,1]范围) minmax_scaler = MinMaxScaler() X_normalized = minmax_scaler.fit_transform(X) print("标准化前特征范围:") print(f"最小值: {X.min().values}, 最大值: {X.max().values}") print("\n标准化后特征范围:") print(f"最小值: {X_scaled.min(axis=0)}, 最大值: {X_scaled.max(axis=0)}") 3.3 特征工程 虽然鸢尾花数据集的特征已经很直观,但在实际项目中,我们经常需要创建新特征: # 创建新特征:花萼面积 df['sepal_area'] = df['sepal length (cm)'] * df['sepal width (cm)'] # 创建新特征:花瓣面积 df['petal_area'] = df['petal length (cm)'] * df['petal width (cm)'] # 创建新特征:花萼与花瓣面积比 df['area_ratio'] = df['sepal_area'] / df['petal_area'] # 查看新特征 print("添加新特征后的数据:") print(df[['sepal_area', 'petal_area', 'area_ratio']].head()) 4. 数据集划分 在机器学习中,我们需要将数据集划分为训练集和测试集,以便评估模型的泛化能力: from sklearn.model_selection import train_test_split # 使用原始特征 X = df[features] y = df['target'] # 划分数据集:70%训练,30%测试 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) print(f"训练集大小: {X_train.shape[0]}") print(f"测试集大小: {X_test.shape[0]}") print(f"训练集类别分布: {np.bincount(y_train)}") print(f"测试集类别分布: {np.bincount(y_test)}") # 使用新特征 X_enhanced = df[features + ['sepal_area', 'petal_area', 'area_ratio']] X_train_enhanced, X_test_enhanced, y_train_enhanced, y_test_enhanced = train_test_split( X_enhanced, y, test_size=0.3, random_state=42, stratify=y ) 关键参数说明: test_size=0.3 :测试集占30% random_state=42 :随机种子,确保结果可复现 stratify=y :按类别比例分层抽样,保证训练集和测试集的类别分布一致 5. 模型训练 5.1 选择分类模型 scikit-learn 提供了多种分类算法,我们介绍几种常用的: 5.1.1 逻辑回归(Logistic Regression) from sklearn.linear_model import LogisticRegression # 创建模型 lr_model = LogisticRegression(random_state=42, max_iter=200) # 训练模型 lr_model.fit(X_train, y_train) # 查看模型参数 print("逻辑回归模型参数:") print(f"系数: {lr_model.coef_}") print(f"截距: {lr_model.intercept_}") 5.1.2 决策树(Decision Tree) from sklearn.tree import DecisionTreeClassifier # 创建模型 dt_model = DecisionTreeClassifier( max_depth=3, # 最大深度 min_samples_split=2, # 内部节点再划分所需最小样本数 random_state=42 ) # 训练模型 dt_model.fit(X_train, y_train) # 可视化决策树 from sklearn.tree import plot_tree plt.figure(figsize=(15, 10)) plot_tree(dt_model, feature_names=features, class_names=iris.target_names, filled=True, rounded=True) plt.title('决策树可视化') plt.show() 5.1.3 随机森林(Random Forest) from sklearn.ensemble import RandomForestClassifier # 创建模型 rf_model = RandomForestClassifier( n_estimators=100, # 树的数量 max_depth=None, # 最大深度 min_samples_split=2, # 分裂所需最小样本数 random_state=42, n_jobs=-1 # 使用所有CPU核心 ) # 训练模型 rf_model.fit(X_train, y_train) # 查看特征重要性 feature_importance = pd.DataFrame({ 'feature': features, 'importance': rf_model.feature_importances_ }).sort_values('importance', ascending=False) print("特征重要性排序:") print(feature_importance) 5.1.4 支持向量机(SVM) from sklearn.svm import SVC # 创建模型 svm_model = SVC( kernel='rbf', # 核函数 C=1.0, # 正则化参数 gamma='scale', # 核系数 random_state=42, probability=True # 启用概率预测 ) # 训练模型 svm_model.fit(X_train, y_train) 5.1.5 K近邻(K-Nearest Neighbors) from sklearn.neighbors import KNeighborsClassifier # 创建模型 knn_model = KNeighborsClassifier( n_neighbors=5, # 邻居数量 weights='uniform', # 权重函数 algorithm='auto' # 算法 ) # 训练模型 knn_model.fit(X_train, y_train) 5.2 模型训练与预测 训练完成后,我们可以使用模型进行预测: # 使用训练好的模型进行预测 y_pred_lr = lr_model.predict(X_test) y_pred_dt = dt_model.predict(X_test) y_pred_rf = rf_model.predict(X_test) y_pred_svm = svm_model.predict(X_test) y_pred_knn = knn_model.predict(X_test) # 查看预测结果 print("逻辑回归预测结果:", y_pred_lr[:10]) print("真实标签:", y_test.values[:10]) 6. 模型评估 6.1 基础评估指标 6.1.1 准确率(Accuracy) from sklearn.metrics import accuracy_score # 计算准确率 accuracy_lr = accuracy_score(y_test, y_pred_lr) accuracy_dt = accuracy_score(y_test, y_pred_dt) accuracy_rf = accuracy_score(y_test, y_pred_rf) accuracy_svm = accuracy_score(y_test, y_pred_svm) accuracy_knn = accuracy_score(y_test, y_pred_knn) print("各模型准确率:") print(f"逻辑回归: {accuracy_lr:.4f}") print(f"决策树: {accuracy_dt:.4f}") print(f"随机森林: {accuracy_rf:.4f}") print(f"SVM: {accuracy_svm:.4f}") print(f"KNN: {accuracy_knn:.4f}") 6.1.2 混淆矩阵(Confusion Matrix) from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay # 计算混淆矩阵 cm_lr = confusion_matrix(y_test, y_pred_lr) # 可视化混淆矩阵 fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # 逻辑回归混淆矩阵 ConfusionMatrixDisplay(cm_lr, display_labels=iris.target_names).plot(ax=axes[0], cmap='Blues') axes[0].set_title('逻辑回归混淆矩阵') # 随机森林混淆矩阵 cm_rf = confusion_matrix(y_test, y_pred_rf) ConfusionMatrixDisplay(cm_rf, display_labels=iris.target_names).plot(ax=axes[1], cmap='Blues') axes[1].set_title('随机森林混淆矩阵') plt.tight_layout() plt.show() 6.1.3 分类报告(Classification Report) from sklearn.metrics import classification_report # 生成分类报告 report_lr = classification_report(y_test, y_pred_lr, target_names=iris.target_names) print("逻辑回归分类报告:") print(report_lr) report_rf = classification_report(y_test, y_pred_rf, target_names=iris.target_names) print("\n随机森林分类报告:") print(report_rf) 6.2 高级评估指标 6.2.1 ROC曲线和AUC(适用于二分类,多分类需要扩展) from sklearn.metrics import roc_curve, auc from sklearn.preprocessing import label_binarize # 二分类示例:只考虑前两个类别 binary_mask = y_test < 2 X_test_binary = X_test[binary_mask] y_test_binary = y_test[binary_mask] # 训练二分类模型 lr_binary = LogisticRegression(random_state=42) lr_binary.fit(X_train[y_train < 2], y_train[y_train < 2]) # 预测概率 y_pred_proba = lr_binary.predict_proba(X_test_binary)[:, 1] # 计算ROC曲线 fpr, tpr, thresholds = roc_curve(y_test_binary, y_pred_proba) roc_auc = auc(fpr, tpr) # 绘制ROC曲线 plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve (Binary Classification)') plt.legend(loc="lower right") plt.show() 6.2.2 交叉验证(Cross-Validation) from sklearn.model_selection import cross_val_score, StratifiedKFold # 创建交叉验证分割器 cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # 对随机森林模型进行交叉验证 cv_scores = cross_val_score(rf_model, X, y, cv=cv, scoring='accuracy') print(f"交叉验证准确率: {cv_scores}") print(f"平均准确率: {cv_scores.mean():.4f} (+/- {cv_scores.std() * 2:.4f})") # 对多个模型进行交叉验证比较 models = { '逻辑回归': LogisticRegression(random_state=42, max_iter=200), '决策树': DecisionTreeClassifier(random_state=42, max_depth=3), '随机森林': RandomForestClassifier(n_estimators=100, random_state=42), 'SVM': SVC(kernel='rbf', random_state=42), 'KNN': KNeighborsClassifier(n_neighbors=5) } print("\n各模型交叉验证结果:") for name, model in models.items(): scores = cross_val_score(model, X, y, cv=cv, scoring='accuracy') print(f"{name}: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})") 6.3 模型性能可视化 # 比较不同模型的性能 model_names = ['逻辑回归', '决策树', '随机森林', 'SVM', 'KNN'] accuracies = [accuracy_lr, accuracy_dt, accuracy_rf, accuracy_svm, accuracy_knn] plt.figure(figsize=(10, 6)) bars = plt.bar(model_names, accuracies, color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']) plt.ylim(0.9, 1.0) plt.ylabel('准确率') plt.title('不同分类模型性能比较') plt.xticks(rotation=45) # 在柱子上显示数值 for bar, acc in zip(bars, accuracies): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.001, f'{acc:.4f}', ha='center', va='bottom') plt.tight_layout() plt.show() 7. 模型调优 7.1 网格搜索(Grid Search) from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 5, 10, 15], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] } # 创建网格搜索 rf = RandomForestClassifier(random_state=42, n_jobs=-1) grid_search = GridSearchCV( rf, param_grid, cv=5, scoring='accuracy', n_jobs=-1, verbose=1 ) # 执行搜索 grid_search.fit(X_train, y_train) # 输出最佳参数 print("最佳参数:", grid_search.best_params_) print("最佳交叉验证分数:", grid_search.best_score_) # 使用最佳模型 best_rf = grid_search.best_estimator_ y_pred_best = best_rf.predict(X_test) print("测试集准确率:", accuracy_score(y_test, y_pred_best)) 7.2 随机搜索(Randomized Search) from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint # 定义参数分布 param_dist = { 'n_estimators': randint(50, 250), 'max_depth': randint(3, 20), 'min_samples_split': randint(2, 11), 'min_samples_leaf': randint(1, 5) } # 创建随机搜索 random_search = RandomizedSearchCV( rf, param_distributions=param_dist, n_iter=20, # 尝试20种组合 cv=5, scoring='accuracy', random_state=42, n_jobs=-1, verbose=1 ) # 执行搜索 random_search.fit(X_train, y_train) print("最佳参数:", random_search.best_params_) print("最佳分数:", random_search.best_score_) 7.3 早停法(Early Stopping) from sklearn.experimental import enable_halving_search_cv from sklearn.model_selection import HalvingGridSearchCV # 使用连续减半搜索(更高效的网格搜索) param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 5, 10], 'min_samples_split': [2, 5] } halving_search = HalvingGridSearchCV( rf, param_grid, factor=2, # 每轮淘汰一半 resource='n_samples', max_resources=10000, cv=5, scoring='accuracy', n_jobs=-1, random_state=42 ) halving_search.fit(X_train, y_train) print("最佳参数:", halving_search.best_params_) 8. 模型保存与部署 8.1 保存模型 import joblib import pickle # 方法1:使用 joblib(推荐用于 scikit-learn 模型) joblib.dump(best_rf, 'best_random_forest_model.pkl') # 方法2:使用 pickle with open('best_random_forest_model.pkl', 'wb') as f: pickle.dump(best_rf, f) # 保存标准化器等预处理对象 joblib.dump(scaler, 'scaler.pkl') 8.2 加载模型并进行预测 # 加载模型 loaded_model = joblib.load('best_random_forest_model.pkl') loaded_scaler = joblib.load('scaler.pkl') # 创建新数据(模拟实际应用) new_data = np.array([[5.1, 3.5, 1.4, 0.2]]) # 预处理 new_data_scaled = loaded_scaler.transform(new_data) # 预测 prediction = loaded_model.predict(new_data_scaled) prediction_proba = loaded_model.predict_proba(new_data_scaled) print(f"预测类别: {iris.target_names[prediction[0]]}") print(f"预测概率: {dict(zip(iris.target_names, prediction_proba[0]))}") 8.3 构建完整的预测管道 from sklearn.pipeline import Pipeline # 创建完整的处理管道 pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier(n_estimators=100, random_state=42)) ]) # 训练管道 pipeline.fit(X_train, y_train) # 评估管道 print("管道准确率:", pipeline.score(X_test, y_test)) # 保存整个管道 joblib.dump(pipeline, 'iris_classifier_pipeline.pkl') # 使用管道进行预测 loaded_pipeline = joblib.load('iris_classifier_pipeline.pkl') new_prediction = loaded_pipeline.predict(new_data) print("管道预测结果:", iris.target_names[new_prediction[0]]) 9. 实战案例:完整工作流整合 下面是一个完整的、可运行的示例,整合了所有步骤: import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.pipeline import Pipeline import joblib def complete_classification_workflow(): """ 完整的分类预测工作流 """ print("=" * 60) print("鸢尾花分类预测完整工作流") print("=" * 60) # 1. 数据加载 print("\n1. 数据加载...") iris = load_iris() X = iris.data y = iris.target print(f"数据集形状: {X.shape}") print(f"特征: {iris.feature_names}") print(f"类别: {iris.target_names}") # 2. 数据集划分 print("\n2. 数据集划分...") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) print(f"训练集: {X_train.shape[0]} 样本") print(f"测试集: {X_test.shape[0]} 样本") # 3. 创建并训练模型 print("\n3. 模型训练...") pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier( n_estimators=100, max_depth=5, random_state=42, n_jobs=-1 )) ]) pipeline.fit(X_train, y_train) print("模型训练完成!") # 4. 模型评估 print("\n4. 模型评估...") y_pred = pipeline.predict(X_test) print(f"\n测试集准确率: {accuracy_score(y_test, y_pred):.4f}") print("\n分类报告:") print(classification_report(y_test, y_pred, target_names=iris.target_names)) print("\n混淆矩阵:") cm = confusion_matrix(y_test, y_pred) print(cm) # 5. 交叉验证 print("\n5. 交叉验证...") cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) cv_scores = cross_val_score(pipeline, X, y, cv=cv, scoring='accuracy') print(f"交叉验证准确率: {cv_scores}") print(f"平均准确率: {cv_scores.mean():.4f} (+/- {cv_scores.std() * 2:.4f})") # 6. 特征重要性 print("\n6. 特征重要性...") rf_model = pipeline.named_steps['classifier'] importance_df = pd.DataFrame({ 'feature': iris.feature_names, 'importance': rf_model.feature_importances_ }).sort_values('importance', ascending=False) print(importance_df) # 7. 保存模型 print("\n7. 保存模型...") joblib.dump(pipeline, 'iris_classifier_final.pkl') print("模型已保存为 'iris_classifier_final.pkl'") # 8. 模拟预测 print("\n8. 模拟预测...") new_sample = np.array([[5.9, 3.0, 5.1, 1.8]]) # virginica 类别 prediction = pipeline.predict(new_sample) probability = pipeline.predict_proba(new_sample) print(f"输入特征: {new_sample[0]}") print(f"预测类别: {iris.target_names[prediction[0]]}") print(f"预测概率: {dict(zip(iris.target_names, probability[0]))}") print("\n" + "=" * 60) print("工作流执行完毕!") print("=" * 60) # 执行完整工作流 if __name__ == "__main__": complete_classification_workflow() 10. 常见问题与解决方案 10.1 数据不平衡问题 from sklearn.utils.class_weight import compute_class_weight # 计算类别权重 class_weights = compute_class_weight( class_weight='balanced', classes=np.unique(y_train), y=y_train ) print("类别权重:", dict(zip(np.unique(y_train), class_weights))) # 在模型中使用类别权重 weighted_rf = RandomForestClassifier( n_estimators=100, class_weight='balanced', # 或者传入自定义权重字典 random_state=42 ) 10.2 特征选择 from sklearn.feature_selection import SelectKBest, f_classif # 选择最重要的2个特征 selector = SelectKBest(score_func=f_classif, k=2) X_train_selected = selector.fit_transform(X_train, y_train) X_test_selected = selector.transform(X_test) print("选中的特征:", np.array(features)[selector.get_support()]) # 训练并评估 rf_selected = RandomForestClassifier(n_estimators=100, random_state=42) rf_selected.fit(X_train_selected, y_train) print("特征选择后准确率:", rf_selected.score(X_test_selected, y_test)) 10.3 处理类别特征 from sklearn.preprocessing import OneHotEncoder, LabelEncoder # 如果有类别特征 # 假设我们有一个新的类别特征 'color' # df['color'] = ['red', 'blue', 'green'] * 50 # 标签编码(适用于有序类别) label_encoder = LabelEncoder() # df['color_encoded'] = label_encoder.fit_transform(df['color']) # 独热编码(适用于无序类别) # encoder = OneHotEncoder(sparse=False) # color_encoded = encoder.fit_transform(df[['color']]) 11. 最佳实践建议 始终从简单模型开始 :先尝试逻辑回归等简单模型,建立基准 使用交叉验证 :避免过拟合,获得更可靠的性能估计 特征工程很重要 :好的特征比复杂的模型更重要 保存所有中间结果 :便于复现和调试 监控训练过程 :使用 verbose 参数查看训练进度 处理缺失值 :根据数据特点选择合适的填充策略 标准化/归一化 :特别是对于基于距离的算法(如KNN、SVM) 使用管道 :避免数据泄露,简化工作流 12. 总结 本教程详细介绍了使用 scikit-learn 进行分类预测的完整流程,从数据准备到模型部署。我们涵盖了: 数据加载和探索性分析 数据预处理(缺失值处理、标准化、特征工程) 数据集划分的最佳实践 多种分类模型的实现和比较 全面的模型评估方法 模型调优技术(网格搜索、随机搜索) 模型保存和部署 实战案例和最佳实践 通过掌握这些技能,你将能够独立完成大多数分类任务。记住,机器学习是一个迭代的过程,需要不断实验、评估和改进。建议你在自己的项目中实践这些技术,并根据具体问题调整方法。 附录:完整代码汇总 # 完整代码汇总(可直接运行) import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.pipeline import Pipeline import joblib # 设置随机种子 np.random.seed(42) # 1. 加载数据 iris = load_iris() X, y = iris.data, iris.target # 2. 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42, stratify=y ) # 3. 创建模型管道 models = { '逻辑回归': Pipeline([('scaler', StandardScaler()), ('clf', LogisticRegression(random_state=42, max_iter=200))]), '决策树': Pipeline([('scaler', StandardScaler()), ('clf', DecisionTreeClassifier(random_state=42, max_depth=3))]), '随机森林': Pipeline([('scaler', StandardScaler()), ('clf', RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1))]), 'SVM': Pipeline([('scaler', StandardScaler()), ('clf', SVC(kernel='rbf', random_state=42, probability=True))]), 'KNN': Pipeline([('scaler', StandardScaler()), ('clf', KNeighborsClassifier(n_neighbors=5))]) } # 4. 训练和评估 results = {} for name, model in models.items(): # 训练 model.fit(X_train, y_train) # 预测 y_pred = model.predict(X_test) # 评估 accuracy = accuracy_score(y_test, y_pred) results[name] = accuracy print(f"\n{name} - 准确率: {accuracy:.4f}") print(classification_report(y_test, y_pred, target_names=iris.target_names, digits=4)) # 5. 比较结果 print("\n" + "="*50) print("模型性能比较:") for name, acc in sorted(results.items(), key=lambda x: x[1], reverse=True): print(f"{name}: {acc:.4f}") # 6. 保存最佳模型 best_model_name = max(results, key=results.get) best_model = models[best_model_name] joblib.dump(best_model, f'best_{best_model_name}_model.pkl') print(f"\n最佳模型 '{best_model_name}' 已保存") # 7. 交叉验证 print("\n交叉验证结果:") cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) for name, model in models.items(): scores = cross_val_score(model, X, y, cv=cv, scoring='accuracy') print(f"{name}: {scores.mean():.4f} (+/- {scores.std() * 2:.4f})") 这个完整的代码示例展示了如何系统地进行分类预测任务。你可以直接运行这段代码,或者根据自己的需求进行修改和扩展。