scikit learn 图像识别与处理实战指南 从零基础入门到掌握核心算法与实际应用技巧

引言:为什么选择 scikit-learn 进行图像识别?
在人工智能和机器学习领域,图像识别是一个令人兴奋且应用广泛的方向。对于初学者来说,scikit-learn 是一个完美的起点。它是一个基于 Python 的开源机器学习库,提供了简单易用的 API 和丰富的算法实现,特别适合快速原型开发和学习机器学习基础。
虽然深度学习框架(如 TensorFlow、PyTorch)在复杂的图像识别任务中表现出色,但 scikit-learn 在以下场景中仍然具有重要价值:
快速验证想法
:在投入深度学习之前,用 scikit-learn 快速验证特征工程和基础模型的效果
理解机器学习基础
:通过 scikit-learn 学习机器学习的核心概念,如特征提取、模型训练、评估等
中小规模数据集
:对于数据量不大的项目,scikit-learn 的传统机器学习算法往往足够有效
可解释性要求高的场景
:传统机器学习模型通常比深度学习模型更容易解释
本指南将带你从零基础开始,逐步掌握使用 scikit-learn 进行图像识别的核心技能,包括数据预处理、特征提取、模型训练、评估优化以及实际应用技巧。
第一部分:环境搭建与基础知识
1.1 安装必要的库
首先,我们需要安装 scikit-learn 及其依赖库。建议使用 Anaconda 或 pip 进行安装:
# 使用 pip 安装
pip install scikit-learn numpy matplotlib pillow opencv-python

# 或者使用 conda 安装
conda install scikit-learn numpy matplotlib pillow opencv-python
1.2 理解图像数据的基本表示
在计算机中,图像通常被表示为多维数组(矩阵)。对于彩色图像,它是一个三维数组:(高度, 宽度, 3),其中最后一个维度表示颜色通道(RGB)。对于灰度图像,它是一个二维数组:(高度, 宽度)。
让我们用 Python 代码来理解这一点:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# 读取一张图像
image = Image.open(‘example.jpg’) # 请替换为你的图像路径
image_array = np.array(image)

print(f”图像形状: {image_array.shape}”)
print(f”数据类型: {image_array.dtype}”)
print(f”像素值范围: {image_array.min()} – {image_array.max()}”)

# 显示图像
plt.imshow(image_array)
plt.axis(‘off’)
plt.show()
1.3 scikit-learn 的核心概念
在使用 scikit-learn 进行图像识别之前,需要理解几个核心概念:
特征(Features)
:将图像转换为机器学习模型可以处理的数值向量
标签(Labels)
:图像对应的类别或目标值
估计器(Estimator)
:实现了机器学习算法的对象,如分类器、回归器
管道(Pipeline)
:将多个处理步骤(如特征提取、标准化、模型训练)串联起来
第二部分:数据准备与预处理
2.1 加载图像数据集
scikit-learn 内置了一些数据集,但对于自定义图像数据,我们需要自己加载。这里介绍两种常用方法:
方法一:使用
load_files
加载组织好的文件夹
假设你的图像数据按以下结构组织:
dataset/
├── class1/
│ ├── image1.jpg
│ ├── image2.jpg
│ └── …
├── class2/
│ ├── image1.jpg
│ ├── image2.jpg
│ └── …
└── class3/
├── image1.jpg
├── image2.jpg
└── …
from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
import numpy as np
from PIL import Image
import os

def load_images_from_folder(base_path, target_size=(64, 64)):
“””
从文件夹加载图像并转换为固定尺寸
“””
data = []
labels = []
class_names = os.listdir(base_path)

for class_name in class_names:
class_path = os.path.join(base_path, class_name)
if os.path.isdir(class_path):
for file_name in os.listdir(class_path):
file_path = os.path.join(class_path, file_name)
if os.path.isfile(file_path):
try:
# 打开并调整图像大小
img = Image.open(file_path).convert(‘RGB’)
img = img.resize(target_size)
img_array = np.array(img)
data.append(img_array)
labels.append(class_name)
except Exception as e:
print(f”无法加载 {file_path}: {e}”)

return np.array(data), np.array(labels)

# 使用示例
# X, y = load_images_from_folder(‘dataset’)
# print(f”加载了 {len(X)} 张图像,形状为 {X[0].shape}”)
方法二:使用
fetch_lfw_people
加载人脸识别数据集
scikit-learn 提供了 LFW(Labeled Faces in the Wild)数据集,适合练习人脸识别:
from sklearn.datasets import fetch_lfw_people
import matplotlib.pyplot as plt

# 加载 LFW 数据集
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

X = lfw_people.data # 图像数据(已展平)
y = lfw_people.target # 标签
target_names = lfw_people.target_names # 类别名称

print(f”图像形状: {X.shape}”)
print(f”标签形状: {y.shape}”)
print(f”类别数量: {len(target_names)}”)
print(f”类别名称: {target_names}”)

# 显示一些样本
fig, axes = plt.subplots(2, 5, figsize=(12, 5))
for i, ax in enumerate(axes.flat):
if i < len(X): ax.imshow(X[i].reshape(lfw_people.images.shape[1:]), cmap='gray') ax.set_title(target_names[y[i]]) ax.axis('off') plt.tight_layout() plt.show() 2.2 数据预处理技巧 2.2.1 图像标准化 from sklearn.preprocessing import StandardScaler # 假设 X 是形状为 (n_samples, height, width, channels) 的数组 # 首先需要展平为 (n_samples, height * width * channels) X_flat = X.reshape(X.shape[0], -1) # 标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X_flat) print(f"标准化前: mean={X_flat.mean():.2f}, std={X_flat.std():.2f}") print(f"标准化后: mean={X_scaled.mean():.2f}, std={X_scaled.std():.2f}") 2.2.2 数据增强(简单版) 虽然 scikit-learn 本身不提供复杂的数据增强功能,但我们可以通过简单的变换来增加数据多样性: import random from scipy.ndimage import rotate, shift def augment_image(image, max_shift=5, max_angle=15): """ 简单的数据增强:平移和旋转 """ # 随机平移 shift_x = random.randint(-max_shift, max_shift) shift_y = random.randint(-max_shift, max_shift) augmented = shift(image, (shift_x, shift_y)) # 随机旋转 angle = random.randint(-max_angle, max_angle) augmented = rotate(augmented, angle, reshape=False) # 确保值在合理范围内 augmented = np.clip(augmented, 0, 255).astype(np.uint8) return augmented # 使用示例 # augmented_image = augment_image(original_image) 第三部分:特征提取技术 3.1 原始像素作为特征(最简单但效果有限) 直接将图像展平为向量作为特征: from sklearn.svm import SVC from sklearn.model_selection import train_test_split # 假设 X 是原始图像数组 (n_samples, height, width, channels) X_flat = X.reshape(X.shape[0], -1) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X_flat, y, test_size=0.2, random_state=42 ) # 训练一个简单的 SVM 分类器 svm = SVC(kernel='linear', probability=True) svm.fit(X_train, y_train) # 评估 accuracy = svm.score(X_test, y_test) print(f"使用原始像素的准确率: {accuracy:.3f}") 优点 :实现简单 缺点 :对光照、角度变化敏感,维度灾难 3.2 HOG(方向梯度直方图)特征 HOG 是一种非常有效的图像特征,特别适合行人检测等任务。它通过计算图像局部区域的梯度方向分布来描述图像。 from skimage.feature import hog from skimage import data, exposure import matplotlib.pyplot as plt # 示例:计算并可视化 HOG 特征 image = data.astronaut() # 使用内置的示例图像 image_gray = data.astronaut().mean(axis=2) # 转为灰度 # 计算 HOG 特征 fd, hog_image = hog( image_gray, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True, channel_axis=-1 ) # 可视化 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) ax1.imshow(image_gray, cmap='gray') ax1.set_title('原始图像') ax2.imshow(hog_image, cmap='gray') ax2.set_title('HOG 特征可视化') plt.show() print(f"HOG 特征维度: {fd.shape}") 在 scikit-learn 中使用 HOG 特征进行图像分类 : from skimage.feature import hog from sklearn.svm import LinearSVC from sklearn.metrics import classification_report def extract_hog_features(images, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1)): """ 从图像列表中提取 HOG 特征 """ hog_features = [] for image in images: # 如果是多通道图像,转为灰度 if len(image.shape) == 3: image_gray = image.mean(axis=2) else: image_gray = image # 计算 HOG fd = hog( image_gray, orientations=orientations, pixels_per_cell=pixels_per_cell, cells_per_block=cells_per_block, visualize=False ) hog_features.append(fd) return np.array(hog_features) # 使用示例(假设 X_train, X_test 是图像数组) # X_train_hog = extract_hog_features(X_train) # X_test_hog = extract_hog_features(X_test) # 训练分类器 # svm_hog = LinearSVC(random_state=42) # svm_hog.fit(X_train_hog, y_train) # 评估 # y_pred = svm_hog.predict(X_test_hog) # print(classification_report(y_test, y_pred)) 3.3 局部二值模式(LBP)特征 LBP 是一种纹理描述符,对光照变化具有很好的鲁棒性。 from skimage.feature import local_binary_pattern from skimage import data # 示例:计算 LBP 特征 image = data.camera() # 内置的灰度图像 # 计算 LBP radius = 3 n_points = 8 * radius lbp = local_binary_pattern(image, n_points, radius, method='uniform') # 可视化 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) ax1.imshow(image, cmap='gray') ax1.set_title('原始图像') ax2.imshow(lbp, cmap='gray') ax2.set_title('LBP 特征') plt.show() # 统计 LBP 直方图作为特征 lbp_hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, n_points+3), range=(0, n_points+2)) lbp_hist = lbp_hist.astype("float") lbp_hist /= (lbp_hist.sum() + 1e-7) # 归一化 print(f"LBP 直方图特征: {lbp_hist}") 3.4 颜色直方图特征 颜色直方图描述图像中颜色的分布,对形状变化不敏感,但对光照变化敏感。 def extract_color_histogram(image, bins=(8, 8, 8)): """ 提取颜色直方图特征 """ # 计算每个通道的直方图 hist = np.histogramdd( image.reshape(-1, 3), bins=bins, range=[(0, 256), (0, 256), (0, 256)] )[0] # 归一化 hist = hist / hist.sum() return hist.flatten() # 使用示例 # color_hist = extract_color_histogram(color_image) 3.5 结合多种特征 在实际应用中,结合多种特征往往能获得更好的效果: def extract_combined_features(image): """ 结合 HOG 和颜色直方图特征 """ # HOG 特征(灰度) if len(image.shape) == 3: image_gray = image.mean(axis=2) else: image_gray = image hog_feat = hog( image_gray, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1) ) # 颜色直方图(仅对彩色图像) if len(image.shape) == 3: color_hist = extract_color_histogram(image) # 合并特征 combined = np.concatenate([hog_feat, color_hist]) else: combined = hog_feat return combined # 使用示例 # X_combined = np.array([extract_combined_features(img) for img in X]) 第四部分:核心算法与模型训练 4.1 支持向量机(SVM) SVM 是图像分类中最常用的算法之一,特别适合高维特征。 from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV from sklearn.metrics import accuracy_score, classification_report # 假设我们已经提取了特征 X_features # X_train, X_test, y_train, y_test = train_test_split(X_features, y, test_size=0.2) # 创建 SVM 分类器 svm = SVC(kernel='rbf', probability=True, random_state=42) # 定义参数网格用于调优 param_grid = { 'C': [0.1, 1, 10, 100], 'gamma': ['scale', 'auto', 0.001, 0.01, 0.1] } # 网格搜索 grid_search = GridSearchCV(svm, param_grid, cv=3, n_jobs=-1, verbose=1) grid_search.fit(X_train, y_train) print(f"最佳参数: {grid_search.best_params_}") print(f"最佳交叉验证分数: {grid_search.best_score_:.3f}") # 使用最佳模型 best_svm = grid_search.best_estimator_ y_pred = best_svm.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"测试集准确率: {accuracy:.3f}") print("\n分类报告:") print(classification_report(y_test, y_pred)) 4.2 随机森林(Random Forest) 随机森林对噪声和过拟合有较好的鲁棒性,且训练速度较快。 from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score # 创建随机森林分类器 rf = RandomForestClassifier( n_estimators=100, max_depth=20, min_samples_split=5, random_state=42, n_jobs=-1 ) # 交叉验证 cv_scores = cross_val_score(rf, X_train, y_train, cv=5) print(f"交叉验证准确率: {cv_scores.mean():.3f} (+/- {cv_scores.std():.3f})") # 训练并评估 rf.fit(X_train, y_train) y_pred = rf.predict(X_test) print(f"测试集准确率: {accuracy_score(y_test, y_pred):.3f}") # 特征重要性分析 if hasattr(rf, 'feature_importances_'): importances = rf.feature_importances_ indices = np.argsort(importances)[::-1] print(f"前10个重要特征: {importances[indices[:10]]}") 4.3 K近邻(KNN) KNN 是一种简单但有效的算法,特别适合小数据集。 from sklearn.neighbors import KNeighborsClassifier # 创建 KNN 分类器 knn = KNeighborsClassifier(n_neighbors=5, weights='distance', n_jobs=-1) # 训练 knn.fit(X_train, y_train) # 评估 y_pred = knn.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"KNN 准确率: {accuracy:.3f}") # 预测概率 probabilities = knn.predict_proba(X_test) print(f"预测概率形状: {probabilities.shape}") 4.4 朴素贝叶斯(Naive Bayes) 虽然简单,但在某些高维数据上表现不错。 from sklearn.naive_bayes import GaussianNB # 创建朴素贝叶斯分类器 gnb = GaussianNB() # 训练 gnb.fit(X_train, y_train) # 评估 y_pred = gnb.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"朴素贝叶斯准确率: {accuracy:.3f}") 4.5 梯度提升树(Gradient Boosting) from sklearn.ensemble import GradientBoostingClassifier # 创建梯度提升分类器 gbc = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42 ) # 训练 gbc.fit(X_train, y_train) # 评估 y_pred = gbc.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"梯度提升准确率: {accuracy:.3f}") 4.6 使用 Pipeline 管道 Pipeline 可以将多个步骤串联,使代码更简洁且避免数据泄露: from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC # 创建 Pipeline pipeline = Pipeline([ ('scaler', StandardScaler()), # 标准化 ('svm', SVC(kernel='rbf', probability=True, random_state=42)) # SVM ]) # 训练 pipeline.fit(X_train, y_train) # 评估 accuracy = pipeline.score(X_test, y_test) print(f"Pipeline 准确率: {accuracy:.3f}") # 预测新样本 # new_image_features = extract_features(new_image) # prediction = pipeline.predict([new_image_features]) # probability = pipeline.predict_proba([new_image_features]) 第五部分:模型评估与优化 5.1 评估指标详解 from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report, roc_curve, auc, precision_recall_curve ) import seaborn as sns # 假设 y_test 是真实标签,y_pred 是预测标签,y_prob 是预测概率 # 1. 基础指标 accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, average='weighted') f1 = f1_score(y_test, y_pred, average='weighted') print(f"准确率: {accuracy:.3f}") print(f"精确率: {precision:.3f}") print(f"召回率: {recall:.3f}") print(f"F1分数: {f1:.3f}") # 2. 混淆矩阵 cm = confusion_matrix(y_test, y_pred) plt.figure(figsize=(10, 8)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') plt.title('混淆矩阵') plt.ylabel('真实标签') plt.xlabel('预测标签') plt.show() # 3. 分类报告 print("\n详细分类报告:") print(classification_report(y_test, y_pred)) # 4. ROC 曲线和 AUC(二分类问题) # 注意:需要将问题转为二分类或对每个类别分别绘制 # 这里以二分类为例 if len(np.unique(y_test)) == 2: fpr, tpr, _ = roc_curve(y_test, y_prob[:, 1]) roc_auc = auc(fpr, tpr) plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {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('Receiver Operating Characteristic') plt.legend(loc="lower right") plt.show() # 5. 精确率-召回率曲线 if len(np.unique(y_test)) == 2: precision, recall, _ = precision_recall_curve(y_test, y_prob[:, 1]) plt.figure() plt.plot(recall, precision, color='blue', lw=2) plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Precision-Recall Curve') plt.show() 5.2 交叉验证 from sklearn.model_selection import cross_val_score, StratifiedKFold # 简单交叉验证 cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) scores = cross_val_score(pipeline, X, y, cv=cv, scoring='accuracy') print(f"交叉验证准确率: {scores.mean():.3f} (+/- {scores.std():.3f})") # 详细交叉验证结果 for fold, (train_idx, val_idx) in enumerate(cv.split(X, y)): X_train_fold, X_val_fold = X[train_idx], X[val_idx] y_train_fold, y_val_fold = y[train_idx], y[val_idx] pipeline.fit(X_train_fold, y_train_fold) score = pipeline.score(X_val_fold, y_val_fold) print(f"Fold {fold + 1}: {score:.3f}") 5.3 超参数调优 from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint, uniform # 使用随机搜索比网格搜索更高效 param_dist = { 'svm__C': uniform(0.1, 100), 'svm__gamma': uniform(0.001, 0.1), 'svm__kernel': ['rbf', 'linear'] } random_search = RandomizedSearchCV( pipeline, param_distributions=param_dist, n_iter=20, cv=3, scoring='accuracy', n_jobs=-1, random_state=42, verbose=1 ) random_search.fit(X_train, y_train) print(f"最佳参数: {random_search.best_params_}") print(f"最佳分数: {random_search.best_score_:.3f}") 5.4 处理类别不平衡 from sklearn.utils.class_weight import compute_class_weight # 方法1:使用类别权重 class_weights = compute_class_weight('balanced', classes=np.unique(y_train), y=y_train) class_weight_dict = dict(enumerate(class_weights)) # 在模型中使用 svm_balanced = SVC(kernel='rbf', class_weight=class_weight_dict, random_state=42) svm_balanced.fit(X_train, y_train) # 方法2:使用过采样(需要 imbalanced-learn 库) # from imblearn.over_sampling import SMOTE # smote = SMOTE(random_state=42) # X_resampled, y_resampled = smote.fit_resample(X_train, y_train) 第六部分:实际应用技巧与最佳实践 6.1 特征工程最佳实践 特征选择 :去除低方差特征 from sklearn.feature_selection import VarianceThreshold selector = VarianceThreshold(threshold=0.01) # 移除方差小于0.01的特征 X_selected = selector.fit_transform(X_flat) 特征重要性分析 : # 对于随机森林或梯度提升模型 importances = model.feature_importances_ indices = np.argsort(importances)[::-1] # 可视化前20个重要特征 plt.figure(figsize=(10, 6)) plt.title("Feature Importances") plt.bar(range(20), importances[indices[:20]]) plt.xticks(range(20), indices[:20]) plt.show() 6.2 模型部署与保存 import joblib # 保存模型和预处理器 joblib.dump(pipeline, 'image_classifier.pkl') joblib.dump(scaler, 'scaler.pkl') # 如果单独使用标准化器 # 加载模型 loaded_model = joblib.load('image_classifier.pkl') # 预测新图像 def predict_new_image(image_path, model, feature_extractor): """ 预测新图像的类别 """ # 加载和预处理图像 img = Image.open(image_path).convert('RGB') img = img.resize((64, 64)) img_array = np.array(img) # 提取特征 features = feature_extractor(img_array) # 预测 prediction = model.predict([features]) probability = model.predict_proba([features]) return prediction[0], probability[0] # 使用示例 # pred, prob = predict_new_image('new_image.jpg', loaded_model, extract_combined_features) # print(f"预测类别: {pred}, 概率: {max(prob):.3f}") 6.3 处理大规模数据集 当数据集太大无法一次性加载到内存时: from sklearn.utils import gen_batches def batch_generator(images, labels, batch_size=32): """ 批量生成器 """ n_samples = len(images) indices = np.arange(n_samples) np.random.shuffle(indices) for start in range(0, n_samples, batch_size): end = min(start + batch_size, n_samples) batch_indices = indices[start:end] yield images[batch_indices], labels[batch_indices] # 使用增量学习(部分模型支持) from sklearn.linear_model import SGDClassifier # SGDClassifier 支持 partial_fit sgd = SGDClassifier(loss='log_loss', random_state=42) # 分批训练 for X_batch, y_batch in batch_generator(X, y, batch_size=1000): # 提取特征(这里简化) X_batch_features = X_batch.reshape(X_batch.shape[0], -1) sgd.partial_fit(X_batch_features, y_batch, classes=np.unique(y)) 6.4 可解释性分析 import shap # 注意:SHAP 通常用于表格数据,对于图像需要特殊处理 # 这里展示对特征向量的解释 # 创建 SHAP 解释器 explainer = shap.KernelExplainer(svm.predict_proba, X_train[:100]) # 解释一个样本 shap_values = explainer.shap_values(X_test[0:1]) # 可视化 shap.initjs() shap.force_plot(explainer.expected_value[0], shap_values[0], X_test[0]) 6.5 模型集成 from sklearn.ensemble import VotingClassifier # 创建多个基础模型 estimators = [ ('svm', SVC(kernel='rbf', probability=True, random_state=42)), ('rf', RandomForestClassifier(n_estimators=100, random_state=42)), ('knn', KNeighborsClassifier(n_neighbors=5)) ] # 硬投票(多数表决) voting_hard = VotingClassifier(estimators=estimators, voting='hard') voting_hard.fit(X_train, y_train) print(f"硬投票准确率: {voting_hard.score(X_test, y_test):.3f}") # 软投票(概率平均) voting_soft = VotingClassifier(estimators=estimators, voting='soft') voting_soft.fit(X_train, y_train) print(f"软投票准确率: {voting_soft.score(X_test, y_test):.3f}") 第七部分:完整项目实战示例 7.1 人脸识别项目 让我们用 LFW 数据集完成一个完整的人脸识别项目: from sklearn.datasets import fetch_lfw_people from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.svm import SVC from sklearn.metrics import classification_report, confusion_matrix from sklearn.decomposition import PCA import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 1. 加载数据 print("正在加载 LFW 数据集...") lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) X = lfw_people.data y = lfw_people.target target_names = lfw_people.target_names print(f"数据形状: {X.shape}") print(f"类别数量: {len(target_names)}") # 2. 数据预处理 # 标准化 X_scaled = X / 255.0 # PCA 降维(可选,但能加速训练) n_components = 150 pca = PCA(n_components=n_components, whiten=True, random_state=42) X_pca = pca.fit_transform(X_scaled) print(f"PCA 后形状: {X_pca.shape}") # 3. 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X_pca, y, test_size=0.25, random_state=42, stratify=y ) # 4. 模型训练与调优 print("开始训练 SVM 模型...") param_grid = { 'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001] } grid_search = GridSearchCV( SVC(kernel='rbf', class_weight='balanced', random_state=42), param_grid, cv=3, n_jobs=-1, verbose=1 ) grid_search.fit(X_train, y_train) print(f"最佳参数: {grid_search.best_params_}") print(f"最佳交叉验证分数: {grid_search.best_score_:.3f}") # 5. 评估 best_model = grid_search.best_estimator_ y_pred = best_model.predict(X_test) print("\n测试集性能:") print(classification_report(y_test, y_pred, target_names=target_names)) # 6. 混淆矩阵可视化 cm = confusion_matrix(y_test, y_pred) plt.figure(figsize=(10, 8)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=target_names, yticklabels=target_names) plt.title('人脸识别混淆矩阵') plt.ylabel('真实身份') plt.xlabel('预测身份') plt.xticks(rotation=45) plt.yticks(rotation=0) plt.tight_layout() plt.show() # 7. 可视化一些预测结果 def plot_predictions(X, y_true, y_pred, target_names, n_cols=5): """ 可视化预测结果 """ n_samples = len(X) n_rows = (n_cols + n_samples - 1) // n_cols fig, axes = plt.subplots(n_rows, n_cols, figsize=(15, 3*n_rows)) if n_rows == 1: axes = axes.reshape(1, -1) for i, ax in enumerate(axes.flat): if i < n_samples: # PCA 后的数据需要逆变换才能显示图像 img = pca.inverse_transform(X[i]) img = img.reshape(lfw_people.images.shape[1:]) ax.imshow(img, cmap='gray') color = 'green' if y_true[i] == y_pred[i] else 'red' ax.set_title(f"真: {target_names[y_true[i]]}\n预: {target_names[y_pred[i]]}", color=color, fontsize=8) ax.axis('off') else: ax.axis('off') plt.tight_layout() plt.show() # 可视化前20个预测 plot_predictions(X_test[:20], y_test[:20], y_pred[:20], target_names) # 8. 保存模型 import joblib joblib.dump(best_model, 'face_recognition_model.pkl') joblib.dump(pca, 'pca_transform.pkl') print("模型已保存") 7.2 手写数字识别项目 from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, classification_report import matplotlib.pyplot as plt import numpy as np # 1. 加载数据 digits = load_digits() X = digits.data y = digits.target images = digits.images print(f"数据形状: {X.shape}") print(f"类别数量: {len(np.unique(y))}") # 2. 可视化一些样本 fig, axes = plt.subplots(2, 5, figsize=(10, 4)) for i, ax in enumerate(axes.flat): ax.imshow(images[i], cmap='gray') ax.set_title(f"标签: {y[i]}") ax.axis('off') plt.tight_layout() plt.show() # 3. 划分数据集 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) # 4. 训练随机森林 rf = RandomForestClassifier( n_estimators=100, max_depth=20, min_samples_split=5, random_state=42, n_jobs=-1 ) rf.fit(X_train, y_train) # 5. 评估 y_pred = rf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"准确率: {accuracy:.3f}") print("\n分类报告:") print(classification_report(y_test, y_pred)) # 6. 特征重要性分析 importances = rf.feature_importances_ # 重塑为8x8图像以可视化重要性 importance_map = importances.reshape(8, 8) plt.figure(figsize=(6, 6)) plt.imshow(importance_map, cmap='hot', interpolation='nearest') plt.title('像素重要性热图') plt.colorbar() plt.show() # 7. 预测新样本 def predict_digit(image_array, model): """ 预测单个手写数字 image_array: 8x8 数组 """ # 展平为1D数组 flattened = image_array.reshape(1, -1) prediction = model.predict(flattened) probability = model.predict_proba(flattened) return prediction[0], probability[0] # 使用示例 # new_digit = images[0] # 使用第一个样本作为示例 # pred, prob = predict_digit(new_digit, rf) # print(f"预测数字: {pred}, 置信度: {max(prob):.3f}") 第八部分:常见问题与解决方案 8.1 内存不足问题 问题 :图像数据太大,无法一次性加载到内存。 解决方案 : 使用生成器 :如前面提到的 batch_generator 降采样 :减小图像尺寸 特征选择 :减少特征维度 使用磁盘缓存 :使用 joblib.Memory from joblib import Memory import tempfile # 创建临时缓存目录 cachedir = tempfile.mkdtemp() memory = Memory(location=cachedir, verbose=0) @memory.cache def extract_features_cached(image_paths): """ 缓存特征提取结果 """ features = [] for path in image_paths: img = Image.open(path) # 提取特征... features.append(...) return np.array(features) 8.2 过拟合问题 症状 :训练准确率高,测试准确率低。 解决方案 : 增加正则化 :增大 SVM 的 C 参数,或使用 L1/L2 正则化 增加数据 :使用数据增强 简化模型 :减少特征数量,使用更简单的模型 交叉验证 :使用更严格的交叉验证 早停 :监控验证集性能 # 使用交叉验证选择最佳模型复杂度 from sklearn.model_selection import validation_curve param_range = [0.01, 0.1, 1, 10, 100] train_scores, test_scores = validation_curve( SVC(), X_train, y_train, param_name="C", param_range=param_range, cv=5, scoring="accuracy", n_jobs=-1 ) train_mean = np.mean(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) plt.figure(figsize=(8, 6)) plt.plot(param_range, train_mean, label="Training score", color="blue") plt.plot(param_range, test_mean, label="Cross-validation score", color="green") plt.xscale('log') plt.xlabel("C") plt.ylabel("Accuracy") plt.title("Validation Curve") plt.legend() plt.show() 8.3 类别不平衡 症状 :某些类别预测准确率极低。 解决方案 : 类别权重 :如前面提到的 class_weight='balanced' 过采样/欠采样 :使用 SMOTE 等算法 评估指标 :使用 F1-score 而不是准确率 阈值调整 :调整分类阈值 # 阈值调整示例(二分类) from sklearn.metrics import f1_score best_threshold = 0.5 best_f1 = 0 for threshold in np.arange(0.1, 0.9, 0.05): y_pred_threshold = (y_prob[:, 1] >= threshold).astype(int)
f1 = f1_score(y_test, y_pred_threshold)
if f1 > best_f1:
best_f1 = f1
best_threshold = threshold

print(f”最佳阈值: {best_threshold:.2f}, 最佳 F1: {best_f1:.3f}”)
8.4 特征维度灾难
症状
:特征数量远大于样本数量,模型训练缓慢且过拟合。
解决方案
:
PCA 降维
:如前面示例
特征选择
:使用 SelectKBest 或基于模型的特征选择
使用线性模型
:线性模型对高维数据更友好
from sklearn.feature_selection import SelectKBest, f_classif

# 选择前 k 个最佳特征
k = 100
selector = SelectKBest(score_func=f_classif, k=k)
X_selected = selector.fit_transform(X_train, y_train)
X_test_selected = selector.transform(X_test)

print(f”特征选择后维度: {X_selected.shape}”)
8.5 模型保存与加载问题
问题
:保存的模型无法加载或版本不兼容。
解决方案
:
固定随机种子
:确保可重现性
版本控制
:记录 scikit-learn 版本
使用 ONNX
:跨框架模型格式
完整保存
:保存所有预处理步骤
# 完整保存示例
model_package = {
‘model’: best_model,
‘scaler’: scaler,
‘pca’: pca,
‘feature_extractor’: extract_combined_features,
‘class_names’: target_names,
‘metadata’: {
‘sklearn_version’: ‘1.3.0’,
‘training_date’: ‘2024-01-15’,
‘accuracy’: accuracy
}
}

joblib.dump(model_package, ‘complete_model_package.pkl’)

# 加载完整包
loaded_package = joblib.load(‘complete_model_package.pkl’)
model = loaded_package[‘model’]
scaler = loaded_package[‘scaler’]
第九部分:进阶技巧与最新趋势
9.1 与深度学习结合
虽然 scikit-learn 不直接支持深度学习,但可以与深度学习特征结合:
# 假设你有一个预训练的 CNN 模型(如 ResNet)提取特征
# 这里用随机特征模拟
def extract_deep_features(images):
“””
使用预训练 CNN 提取特征(示例)
“””
# 实际中,你会使用 torchvision 或 tensorflow
# 这里用随机特征模拟
return np.random.randn(len(images), 512)

# 提取深度特征
# deep_features = extract_deep_features(X)

# 然后用 scikit-learn 分类器
# svm_deep = SVC()
# svm_deep.fit(deep_features_train, y_train)
9.2 自监督学习特征
# 使用 PCA 作为简单的自监督特征学习
from sklearn.decomposition import PCA

# 在无标签数据上训练 PCA
pca_unsupervised = PCA(n_components=128)
pca_unsupervised.fit(X_flat)

# 使用 PCA 特征进行分类
X_pca_features = pca_unsupervised.transform(X_flat)
9.3 主动学习
from sklearn.cluster import KMeans

# 主动学习:选择最具信息量的样本进行标注
def select_samples_for_labeling(X, n_samples=100):
“””
使用 KMeans 选择代表性样本
“””
kmeans = KMeans(n_clusters=n_samples, random_state=42)
kmeans.fit(X)

# 选择每个聚类中心最近的样本
selected_indices = []
for i in range(n_samples):
cluster_indices = np.where(kmeans.labels_ == i)[0]
if len(cluster_indices) > 0:
# 选择距离中心最近的样本
center = kmeans.cluster_centers_[i]
distances = np.linalg.norm(X[cluster_indices] – center, axis=1)
selected_idx = cluster_indices[np.argmin(distances)]
selected_indices.append(selected_idx)

return selected_indices

# 使用示例
# indices_to_label = select_samples_for_labeling(X, n_samples=50)
# print(f”需要标注的样本索引: {indices_to_label}”)
9.4 模型解释性增强
# 使用 LIME 解释图像分类(需要安装 lime)
# pip install lime

from lime import lime_image
from skimage.segmentation import mark_boundaries

def explain_prediction(image, model, feature_extractor):
“””
使用 LIME 解释图像分类预测
“””
# 提取特征
features = feature_extractor(image)

# 预测函数
def predict_fn(images):
# LIME 会传入多个图像扰动
features_list = [feature_extractor(img) for img in images]
return model.predict_proba(features_list)

# 创建解释器
explainer = lime_image.LimeImageExplainer()

# 解释
explanation = explainer.explain_instance(
image,
predict_fn,
top_labels=5,
hide_color=0,
num_samples=1000
)

# 可视化
temp, mask = explanation.get_image_and_mask(
explanation.top_labels[0],
positive_only=True,
num_features=5,
hide_rest=False
)

plt.figure(figsize=(8, 8))
plt.imshow(mark_boundaries(temp, mask))
plt.title(f”解释: {target_names[explanation.top_labels[0]]}”)
plt.axis(‘off’)
plt.show()

# 使用示例
# explain_prediction(test_image, best_model, extract_combined_features)
第十部分:总结与建议
10.1 关键要点回顾
特征工程是核心
:好的特征比复杂的模型更重要
从简单开始
:先用简单模型和特征建立基线
系统化评估
:使用交叉验证和多种评估指标
理解数据
:可视化数据和预测结果
迭代优化
:逐步改进特征和模型
10.2 学习路径建议
基础阶段
:掌握 scikit-learn 基本 API,理解机器学习流程
特征工程
:学习 HOG、LBP、颜色直方图等常用特征
模型调优
:掌握交叉验证、网格搜索、超参数调优
项目实践
:完成至少2-3个完整项目
进阶学习
:探索深度学习、模型解释性、部署等
10.3 推荐资源
官方文档
:scikit-learn.org/stable/
书籍
:《Python Machine Learning》、《Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow》
在线课程
:Coursera 的 Machine Learning 课程
数据集
:UCI Machine Learning Repository, Kaggle
10.4 最终建议
不要过度依赖单一模型
:尝试多种算法
记录实验
:使用笔记本或工具记录每次实验的参数和结果
关注业务目标
:模型指标要与实际需求对齐
保持学习
:机器学习领域发展迅速,持续学习新技术
通过本指南的学习和实践,你将能够熟练使用 scikit-learn 进行图像识别任务,并理解背后的核心原理。记住,实践是最好的老师,多动手做项目才能真正掌握这些技能!