Python面试题:结合Python技术,如何使用Scikit-learn进行监督学习和无监督学习

使用Scikit-learn进行监督学习和无监督学习可以帮助我们构建和评估机器学习模型。下面将分别介绍如何使用Scikit-learn进行这两种类型的学习。

监督学习

监督学习需要训练数据的特征和目标标签。Scikit-learn提供了多种监督学习算法,如线性回归、决策树、支持向量机等。以下是一个简单的监督学习流程示例,使用线性回归进行预测:

  1. 安装Scikit-learn

    确保已安装Scikit-learn库:

    bash 复制代码
    pip install scikit-learn
  2. 加载数据

    可以使用Scikit-learn自带的数据集,或者加载自己的数据集。这里以波士顿房价数据集为例:

    python 复制代码
    from sklearn.datasets import load_boston
    import pandas as pd
    from sklearn.model_selection import train_test_split
    
    # 加载波士顿房价数据集
    boston = load_boston()
    X = pd.DataFrame(boston.data, columns=boston.feature_names)
    y = pd.Series(boston.target)
    
    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  3. 构建模型

    以线性回归为例:

    python 复制代码
    from sklearn.linear_model import LinearRegression
    
    # 初始化线性回归模型
    model = LinearRegression()
    
    # 训练模型
    model.fit(X_train, y_train)
  4. 评估模型

    使用测试集评估模型性能:

    python 复制代码
    from sklearn.metrics import mean_squared_error, r2_score
    
    # 预测
    y_pred = model.predict(X_test)
    
    # 计算均方误差和R²得分
    mse = mean_squared_error(y_test, y_pred)
    r2 = r2_score(y_test, y_pred)
    
    print(f'Mean Squared Error: {mse}')
    print(f'R² Score: {r2}')

无监督学习

无监督学习不需要目标标签,常用于聚类和降维任务。Scikit-learn提供了多种无监督学习算法,如K-means、PCA等。以下是一个简单的无监督学习流程示例,使用K-means进行聚类:

  1. 加载数据

    使用Iris数据集进行聚类分析:

    python 复制代码
    from sklearn.datasets import load_iris
    
    # 加载Iris数据集
    iris = load_iris()
    X = iris.data
  2. 构建模型

    以K-means聚类为例:

    python 复制代码
    from sklearn.cluster import KMeans
    
    # 初始化K-means模型,设定聚类数为3
    kmeans = KMeans(n_clusters=3, random_state=42)
    
    # 训练模型
    kmeans.fit(X)
  3. 分析结果

    查看聚类结果和聚类中心:

    python 复制代码
    # 获取聚类标签
    labels = kmeans.labels_
    
    # 获取聚类中心
    centers = kmeans.cluster_centers_
    
    print(f'Cluster Centers:\n{centers}')
  4. 可视化结果

    可以使用matplotlib进行结果可视化:

    python 复制代码
    import matplotlib.pyplot as plt
    
    # 可视化聚类结果
    plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
    plt.scatter(centers[:, 0], centers[:, 1], c='red', marker='x')
    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.title('K-means Clustering')
    plt.show()

总结

以上是使用Scikit-learn进行监督学习和无监督学习的基本流程。通过这些步骤,您可以快速实现各种机器学习模型的训练、评估和可视化。Scikit-learn还提供了其他多种算法和工具,适用于不同的机器学习任务,可以根据具体需求进行选择和应用。

相关推荐
2501_944452233 小时前
字数统计 Cordova 与 OpenHarmony 混合开发实战
python
骚戴3 小时前
2025 Python AI 实战:零基础调用 LLM API 开发指南
人工智能·python·大模型·llm·api·ai gateway
kobe_OKOK_3 小时前
tdeinge REST API 客户端
python·缓存·django
io_T_T3 小时前
Python os库 os.walk使用(详细教程、带实践)
python
TonyLee0174 小时前
使用argparse模块以及shell脚本
python
Blossom.1185 小时前
Prompt工程与思维链优化实战:从零构建动态Few-Shot与CoT推理引擎
人工智能·分布式·python·智能手机·django·prompt·边缘计算
love530love6 小时前
Windows 11 下 Z-Image-Turbo 完整部署与 Flash Attention 2.8.3 本地编译复盘
人工智能·windows·python·aigc·flash-attn·z-image·cuda加速
MediaTea7 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
jarreyer7 小时前
python,numpy,pandas和matplotlib版本对应关系
python·numpy·pandas
代码or搬砖7 小时前
HashMap源码
开发语言·python·哈希算法