skorch基础使用指南:PyTorch与scikit-learn的无缝集成
skorch 项目地址: https://gitcode.com/gh_mirrors/sko/skorch
概述
skorch是一个强大的Python库,它架起了PyTorch深度学习框架与scikit-learn机器学习生态系统之间的桥梁。通过skorch,开发者可以享受到PyTorch提供的灵活神经网络构建能力,同时又能利用scikit-learn丰富的模型评估、参数调优和流水线功能。
分类任务实践
数据准备
我们首先创建一个简单的二分类数据集:
from sklearn.datasets import make_classification
import numpy as np
# 生成包含1000个样本,每个样本20个特征,其中10个是有效特征的二分类数据集
X, y = make_classification(1000, 20, n_informative=10, random_state=0)
X, y = X.astype(np.float32), y.astype(np.int64)
构建PyTorch模型
定义一个包含两个隐藏层的神经网络分类器:
import torch.nn as nn
import torch.nn.functional as F
class ClassifierModule(nn.Module):
def __init__(self, num_units=10, dropout=0.5):
super().__init__()
self.dense0 = nn.Linear(20, num_units)
self.dropout = nn.Dropout(dropout)
self.dense1 = nn.Linear(num_units, 10)
self.output = nn.Linear(10, 2)
def forward(self, X):
X = F.relu(self.dense0(X))
X = self.dropout(X)
X = F.relu(self.dense1(X))
X = F.softmax(self.output(X), dim=-1)
return X
使用skorch包装模型
from skorch import NeuralNetClassifier
net = NeuralNetClassifier(
ClassifierModule,
max_epochs=20,
lr=0.1,
# device='cuda' # 如需使用GPU训练,取消注释
)
模型训练与评估
net.fit(X, y)
# 预测
y_pred = net.predict(X[:5])
y_proba = net.predict_proba(X[:5])
回归任务实践
数据准备
from sklearn.datasets import make_regression
X_regr, y_regr = make_regression(1000, 20, n_informative=10, random_state=0)
X_regr = X_regr.astype(np.float32)
y_regr = y_regr.astype(np.float32) / 100
y_regr = y_regr.reshape(-1, 1) # 回归任务需要二维目标
构建回归模型
class RegressorModule(nn.Module):
def __init__(self, num_units=10):
super().__init__()
self.dense0 = nn.Linear(20, num_units)
self.dense1 = nn.Linear(num_units, 10)
self.output = nn.Linear(10, 1)
def forward(self, X):
X = F.relu(self.dense0(X))
X = F.relu(self.dense1(X))
X = self.output(X) # 回归任务不需要激活函数
return X
使用skorch包装回归模型
from skorch import NeuralNetRegressor
net_regr = NeuralNetRegressor(
RegressorModule,
max_epochs=20,
lr=0.1,
)
net_regr.fit(X_regr, y_regr)
模型保存与加载
保存整个模型
net.save_params(f_params='model.pkl')
仅保存模型参数
import pickle
with open('model_params.pkl', 'wb') as f:
pickle.dump(net.get_params(), f)
与scikit-learn集成
使用Pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
('scale', StandardScaler()),
('net', net),
])
pipe.fit(X, y)
网格搜索
from sklearn.model_selection import GridSearchCV
params = {
'lr': [0.01, 0.1],
'max_epochs': [10, 20],
'module__num_units': [10, 20],
}
gs = GridSearchCV(net, params, cv=3, scoring='accuracy')
gs.fit(X, y)
高级功能:回调函数
skorch支持多种回调函数,方便在训练过程中添加额外功能:
from skorch.callbacks import EarlyStopping, Checkpoint
callbacks = [
EarlyStopping(patience=5),
Checkpoint(monitor='valid_acc_best')
]
net = NeuralNetClassifier(
ClassifierModule,
max_epochs=50,
lr=0.1,
callbacks=callbacks
)
总结
skorch为PyTorch和scikit-learn之间的互操作性提供了优雅的解决方案,使得:
- PyTorch模型可以像scikit-learn估计器一样使用fit/predict接口
- 能够无缝集成到scikit-learn的Pipeline和GridSearchCV中
- 保留了PyTorch的全部灵活性
- 提供了丰富的回调函数系统
通过本文介绍的基础用法,开发者可以快速上手skorch,构建兼具PyTorch强大功能和scikit-learn便捷性的机器学习解决方案。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考