
关于
使用 scikit-learn 进行 Python 机器学习。用于分类、回归、聚类、模型评估和特征工程。
name: scikit-learn description: 使用 scikit-learn 进行 Python 机器学习。用于分类、回归、聚类、模型评估和 ML 管道。 license: BSD-3-Clause 许可证 metadata: skill-author: K-Dense Inc. risk: unknown source: community
Scikit-learn
概述
本技能为使用 scikit-learn 进行机器学习任务提供全面指导。scikit-learn 是经典机器学习领域的行业标准 Python 库。适用于分类、回归、聚类、降维、数据预处理、模型评估以及构建生产级 ML 管道。
安装
# 使用 uv 安装 scikit-learn
uv pip install scikit-learn
# 可选:安装可视化依赖
uv pip install matplotlib seaborn
# 常用搭配库
uv pip install pandas numpy
适用场景
在以下情况下使用 scikit-learn 技能:
- 构建分类或回归模型
- 执行聚类或降维分析
- 对机器学习数据进行预处理和转换
- 使用交叉验证评估模型性能
- 使用网格搜索或随机搜索调优超参数
- 创建生产级 ML 管道工作流
- 比较不同算法在同一任务上的表现
- 处理结构化(表格)数据和文本数据
- 需要可解释的经典机器学习方法
快速入门
分类示例
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
# 划分数据
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
# 预处理
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# 评估
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))
混合数据完整管道
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier
# 定义特征类型
numeric_features = ['age', 'income']
categorical_features = ['gender', 'occupation']
# 创建预处理管道
numeric_transformer = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
categorical_transformer = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# 组合转换器
preprocessor = ColumnTransformer([
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
])
# 完整管道
model = Pipeline([
('preprocessor', preprocessor),
('classifier', GradientBoostingClassifier(random_state=42))
])
# 拟合与预测
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
核心能力
1. 监督学习
提供全面的分类和回归算法。
主要算法:
- 线性模型:逻辑回归、线性回归、Ridge、Lasso、ElasticNet
- 树模型:决策树、随机森林、梯度提升
- 支持向量机:SVC、SVR(支持多种核函数)
- 集成方法:AdaBoost、投票法、堆叠法
- 神经网络:MLPClassifier、MLPRegressor
- 其他:朴素贝叶斯、K近邻
适用场景:
- 分类:预测离散类别(垃圾邮件检测、图像分类、欺诈检测)
- 回归:预测连续值(价格预测、需求预测)
2. 无监督学习
通过聚类和降维发现无标签数据中的模式。
聚类算法:
- 基于划分:K-Means、MiniBatchKMeans
- 基于密度:DBSCAN、HDBSCAN、OPTICS
- 层次聚类:AgglomerativeClustering
- 概率模型:高斯混合模型
- 其他:MeanShift、SpectralClustering、BIRCH
降维方法:
- 线性:PCA、TruncatedSVD、NMF
- 流形学习:t-SNE、UMAP、Isomap、LLE
- 特征提取:FastICA、LatentDirichletAllocation
适用场景:
- 客户分群、异常检测、数据可视化
- 降低特征维度、探索性数据分析
- 主题建模、图像压缩
3. 模型评估与选择
提供稳健的模型评估、交叉验证和超参数调优工具。
兼容工具
Claude CodeCursor
标签
数据工程
