机器学习之scikit-learn(简称 sklearn)

scikit-learn(简称 sklearn)是 Python 生态中一个非常流行且强大的机器学习库,支持各种机器学习算法和工具。


核心模块和功能

  1. 监督学习 (Supervised Learning):

    • 分类 (Classification):

      • 支持的算法:KNN、SVM、决策树、随机森林、Logistic回归、朴素贝叶斯等。

      • 示例:

        复制代码
        from sklearn.ensemble import RandomForestClassifier
        
        clf = RandomForestClassifier(n_estimators=100, random_state=42)
        clf.fit(X_train, y_train)  # 训练模型
        predictions = clf.predict(X_test)  # 预测
    • 回归 (Regression):

      • 支持的算法:线性回归、Ridge回归、Lasso回归、SVR等。

      • 示例:

        复制代码
        from sklearn.linear_model import LinearRegression
        
        reg = LinearRegression()
        reg.fit(X_train, y_train)  # 拟合数据
        predictions = reg.predict(X_test)  # 预测
  2. 无监督学习 (Unsupervised Learning):

    • 聚类 (Clustering):

      • 支持的算法:K-Means、DBSCAN、层次聚类等。

      • 示例:

        复制代码
        from sklearn.cluster import KMeans
        
        kmeans = KMeans(n_clusters=3, random_state=42)
        kmeans.fit(X)  # 拟合数据
        labels = kmeans.labels_  # 获取聚类标签
    • 降维 (Dimensionality Reduction):

      • 支持的算法:PCA、TSNE、ICA等。

      • 示例:

        复制代码
        from sklearn.decomposition import PCA
        
        pca = PCA(n_components=2)
        X_reduced = pca.fit_transform(X)  # 降维
  3. 模型选择与优化 (Model Selection and Optimization):

    • 交叉验证 (Cross Validation):

      • 使用 cross_val_score 实现简单交叉验证。

      • 示例:

        复制代码
        from sklearn.model_selection import cross_val_score
        
        scores = cross_val_score(clf, X, y, cv=5)  # 5折交叉验证
        print(scores.mean())  # 平均准确率
    • 超参数调优 (Hyperparameter Tuning):

      • 使用 GridSearchCV 或 RandomizedSearchCV。

      • 示例:

        复制代码
        from sklearn.model_selection import GridSearchCV
        
        param_grid = {'n_estimators': [50, 100, 150], 'max_depth': [10, 20, None]}
        grid_search = GridSearchCV(RandomForestClassifier(), param_grid, cv=3)
        grid_search.fit(X_train, y_train)
        print(grid_search.best_params_)  # 最优参数
  4. 预处理 (Preprocessing):

    • 标准化与归一化:

      • 使用 StandardScaler 或 MinMaxScaler。

      • 示例:

        复制代码
        from sklearn.preprocessing import StandardScaler
        
        scaler = StandardScaler()
        X_scaled = scaler.fit_transform(X)
    • 特征选择 (Feature Selection):

      • 支持的方法:SelectKBest、递归特征消除 (RFE) 等。

      • 示例:

        复制代码
        from sklearn.feature_selection import SelectKBest, f_classif
        
        selector = SelectKBest(f_classif, k=10)
        X_new = selector.fit_transform(X, y)

常用工具

  1. 评估指标 (Metrics):

    • 分类指标:准确率、F1分数、ROC曲线等。

      复制代码
      from sklearn.metrics import accuracy_score, classification_report
      
      print(accuracy_score(y_test, y_pred))
      print(classification_report(y_test, y_pred))
    • 回归指标:均方误差 (MSE)、R²等。

      复制代码
      from sklearn.metrics import mean_squared_error, r2_score
      
      print(mean_squared_error(y_test, y_pred))
      print(r2_score(y_test, y_pred))
  2. 数据集工具:

    • 自带数据集加载:如 iris、digits 等。

      复制代码
      from sklearn.datasets import load_iris
      
      data = load_iris()
      X, y = data.data, data.target
    • 数据集拆分:

      复制代码
      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)

完整工作流程示例

以一个分类任务为例,使用随机森林进行训练并评估:

复制代码
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# 1. 加载数据
data = load_iris()
X, y = data.data, data.target

# 2. 数据集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 3. 模型训练
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# 4. 模型预测
y_pred = clf.predict(X_test)

# 5. 模型评估
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))

适用场景

  1. 快速实现基于传统方法的机器学习任务。
  2. 教学或研究中算法的对比实验。
  3. 中小型数据集的机器学习应用。
相关推荐
qq_1588954111118 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
学无止境小袁同学1 天前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴1 天前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
塑料铲子1 天前
你的 Skill 越多越蠢?Token 上下文爆炸的求生指南
机器学习·agent
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5551 天前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展