Python人工智能中scikit-learn模块的使用介绍

Python 中 scikit-learn(sklearn)模块安装与使用详细教程

注意

你可能指的是 scikit-learn(通常缩写为 sklearn),而不是 slearnscikit-learn 是 Python 最流行的机器学习库之一。以下是完整的安装和使用指南。


一、安装 scikit-learn

1. 通过 pip 安装(推荐)
bash 复制代码
pip install scikit-learn
2. 通过 conda 安装(适合 Anaconda 用户)
bash 复制代码
conda install scikit-learn
3. 验证安装
python 复制代码
import sklearn
print(sklearn.__version__)  # 查看版本(应输出类似 1.4.x)

二、快速入门示例:鸢尾花分类

完整代码示例
python 复制代码
# 导入必要模块
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# 1. 加载数据集
iris = load_iris()
X = iris.data  # 特征数据(150个样本,4个特征)
y = iris.target  # 标签(0,1,2 代表三种鸢尾花)

# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 3. 创建并训练模型
model = DecisionTreeClassifier(max_depth=3)
model.fit(X_train, y_train)

# 4. 预测测试集
y_pred = model.predict(X_test)

# 5. 评估准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy:.2f}")  # 输出示例:模型准确率: 1.00

三、核心功能详解

1. 数据预处理
python 复制代码
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

# 数值特征标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_train)

# 分类特征编码
encoder = OneHotEncoder()
encoded_features = encoder.fit_transform(categorical_data)

# 缺失值填充(用均值)
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X_missing)
2. 模型训练与评估
python 复制代码
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# 使用随机森林
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)

# 详细评估报告
report = classification_report(y_test, model.predict(X_test))
print(report)
3. 模型选择与交叉验证
python 复制代码
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC

# 10折交叉验证
scores = cross_val_score(SVC(), X, y, cv=10)
print(f"平均准确率: {scores.mean():.2f} ± {scores.std():.2f}")
4. 管道(Pipeline)整合流程
python 复制代码
from sklearn.pipeline import make_pipeline

# 创建预处理+模型的完整管道
pipeline = make_pipeline(
    StandardScaler(),
    RandomForestClassifier()
)

# 直接训练和预测
pipeline.fit(X_train, y_train)
pipeline.score(X_test, y_test)

四、常用模型速查

任务类型 算法 导入路径
分类 逻辑回归 sklearn.linear_model.LogisticRegression
支持向量机 (SVM) sklearn.svm.SVC
随机森林 sklearn.ensemble.RandomForestClassifier
回归 线性回归 sklearn.linear_model.LinearRegression
梯度提升树 sklearn.ensemble.GradientBoostingRegressor
聚类 K-Means sklearn.cluster.KMeans
降维 PCA sklearn.decomposition.PCA

五、常见问题解决

  1. 导入错误 No module named 'slearn'

    → 确认正确库名是 scikit-learn,导入时用 import sklearn

  2. 安装缓慢/超时

    → 使用国内镜像源:

    bash 复制代码
    pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple
  3. 版本冲突

    → 创建虚拟环境:

    bash 复制代码
    python -m venv myenv
    source myenv/bin/activate  # Linux/macOS
    myenv\Scripts\activate    # Windows
    pip install scikit-learn

六、学习资源推荐

  1. 官方文档:scikit-learn.org
  2. 实用案例库:scikit-learn examples gallery
  3. 经典书籍:《Python机器学习实践指南》
相关推荐
雪隐9 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端
洛宇9 小时前
再谈 AI 时代,程序员的失眠问题。
人工智能
百度Geek说9 小时前
harness-pilot 给代码库加一套"规则说明书"和"自动检查器"
人工智能
程序员cxuan9 小时前
分享一下我最近常用的 10 个 Codex 小技巧。
人工智能·后端·程序员
用户3379225456810 小时前
基于 OKF + RAG 构建 Text2SQL 语义层:让 LLM 真正理解你的数据库
人工智能
把所有砖敲烂10 小时前
MiniMax M3 深度实测:单卡部署、代码生成与性能全解析
人工智能
沉默王二10 小时前
老板:“请说出一个录用你的理由。”我脱口而出:“每个月 AI 支出都超过我的生活费了!”老板愣了一下,随即哈哈大笑:“好吧,你被录用了。”
人工智能·ai编程·claude
黄忠10 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
这token有力气10 小时前
ReAct 循环中陷入"工具调用死循环"
人工智能
黄忠10 小时前
03-跨库链路检索-Neo4j图数据库桥接文档与代码
人工智能