python - 将多种算法与 sklearn 管道进行比较

标签 python algorithm machine-learning scikit-learn

我正在尝试设置一个 scikit-learn 管道来简化我的工作。我面临的问题是我不知道哪种算法(随机森林、朴素贝叶斯、决策树等)最适合,所以我需要尝试每一种算法并比较结果。然而,管道一次只采用一种算法吗?例如下面的管道只采用 SGDClassifier() 作为算法。

pipeline = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', SGDClassifier()),])

如果我想比较不同的算法怎么办?我可以做这样的事情吗?

pipeline = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', SGDClassifier()),
('classifier', MultinomialNB()),])

我不想将其分解为两条管道,因为数据的预处理非常耗时。

提前致谢!

最佳答案

改进 Bruno 的回答,大多数人真正想做的是能够传入任何分类器(不必对每个分类器进行硬编码)以及每个分类器的任何参数。这是执行此操作的简单方法:

创建适用于任何估算器的切换器类

from sklearn.base import BaseEstimator
class ClfSwitcher(BaseEstimator):

def __init__(
    self, 
    estimator = SGDClassifier(),
):
    """
    A Custom BaseEstimator that can switch between classifiers.
    :param estimator: sklearn object - The classifier
    """ 

    self.estimator = estimator


def fit(self, X, y=None, **kwargs):
    self.estimator.fit(X, y)
    return self


def predict(self, X, y=None):
    return self.estimator.predict(X)


def predict_proba(self, X):
    return self.estimator.predict_proba(X)


def score(self, X, y):
    return self.estimator.score(X, y)

现在您可以为估算器参数传入任何内容。您可以按如下方式为传入的任何估算器优化任何参数:

执行超参数优化

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV

pipeline = Pipeline([
    ('tfidf', TfidfVectorizer()),
    ('clf', ClfSwitcher()),
])

parameters = [
    {
        'clf__estimator': [SGDClassifier()], # SVM if hinge loss / logreg if log loss
        'tfidf__max_df': (0.25, 0.5, 0.75, 1.0),
        'tfidf__stop_words': ['english', None],
        'clf__estimator__penalty': ('l2', 'elasticnet', 'l1'),
        'clf__estimator__max_iter': [50, 80],
        'clf__estimator__tol': [1e-4],
        'clf__estimator__loss': ['hinge', 'log', 'modified_huber'],
    },
    {
        'clf__estimator': [MultinomialNB()],
        'tfidf__max_df': (0.25, 0.5, 0.75, 1.0),
        'tfidf__stop_words': [None],
        'clf__estimator__alpha': (1e-2, 1e-3, 1e-1),
    },
]

gscv = GridSearchCV(pipeline, parameters, cv=5, n_jobs=12, return_train_score=False, verbose=3)
gscv.fit(train_data, train_labels)

如何解读clf__estimator__loss

clf__estimator__loss 被解释为任何 estimatorloss 参数,其中 estimator = SGDClassifier() 在最上面的例子,它本身就是 clf 的一个参数,它是一个 ClfSwitcher 对象。

关于python - 将多种算法与 sklearn 管道进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695322/

相关文章:

machine-learning - 如何表示神经网络的期望输出以便与实际输出进行比较?

machine-learning - 机器学习 - 标准化没有理论最大值的特征

python - 如何使用 boto 将文件从 Amazon S3 流式传输到 Rackspace Cloudfiles?

python - 如何使用 Azure Python SDK 获取 Azure VM 正常运行时间/运行时间(运行状态时间)

python - 平均脸-算法

Javascript 算法/函数为可见光谱中的颜色生成 RGB 值

.net - 有没有一种方法可以训练 Encog 神经网络而不将所有训练集加载到内存中?

python - 用Python将完整的csv表写入PDF

python:使用多处理共享巨大的字典

algorithm - 在大集合中寻找最近的邻居