我的sklearn管道中有一个自定义的Transformer,我想知道如何将参数传递给我的Transformer:

在下面的代码中,您可以看到我在Transformer中使用了字典“weight”。我不希望在Transformer中定义该词典,而是从管道中传递它,以便可以在网格搜索中包括该词典。是否可以将字典作为参数传递给我的Transformer?

# My custom Transformer
  class TextExtractor(BaseEstimator, TransformerMixin):
        """Concat the 'title', 'body' and 'code' from the results of
        Stackoverflow query
        Keys are 'title', 'body' and 'code'.
        """
        def fit(self, x, y=None):
            return self

        def transform(self, x):
            # here is the parameter  I want to pass to my transformer
            weight ={'title' : 10, 'body': 1, 'code' : 1}
            x['text'] = weight['title']*x['Title'] +
            weight['body']*x['Body'] +
            weight['code']*x['Code']

            return x['text']

param_grid = {
    'min_df' : [10],
    'max_df' : [0.01],
    'max_features': [200],
    'clf' : [sgd]
    # here is the parameter  I want to pass to my transformer
    'weigth' : [{'title' : 10, 'body': 1, 'code' : 1}, {'title' : 1, 'body':
     1, 'code' : 1}]

}

for g in ParameterGrid(param_grid) :

    classifier_pipe = Pipeline(

    steps=[    ('textextractor', TextExtractor()), #is it possible to pass
                my parameter ?
               ('vectorizer', TfidfVectorizer(max_df=g['max_df'],
                     min_df=g['min_df'], max_features=g['max_features'])),
               ('clf', g['clf']),
            ],
    )

最佳答案

为此,您只需要在类定义的开头添加__init__()方法即可。在此步骤中,您将类TextExtractor定义为采用称为weight的参数。

这是可以做到的:(为了重现性,我之前添加了许多代码行-鉴于您未指定任何内容,我组成了一些虚假数据。我还假设您要对权重进行的操作是乘以字符串?)

# import all the necessary packages
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import ParameterGrid, GridSearchCV
from sklearn.linear_model import SGDClassifier

import pandas as pd
import numpy as np

#Sample data
X = pd.DataFrame({"Title" : ["T1","T2","T3","T4","T5"], "Body": ["B1","B2","B3","B4","B5"], "Code": ["C1","C2","C3","C4","C5"]})
y = np.array([0,0,1,1,1])

#Define the SGDClassifier
sgd = SGDClassifier()

在下面,我仅添加了 init 步骤:
# My custom Transformer

class TextExtractor(BaseEstimator, TransformerMixin):
    """Concat the 'title', 'body' and 'code' from the results of
    Stackoverflow query
    Keys are 'title', 'body' and 'code'.


    """

    def __init__(self, weight = {'title' : 10, 'body': 1, 'code' : 1}):

        self.weight = weight

    def fit(self, x, y=None):
        return self

    def transform(self, x):

        x['text'] = self.weight['title']*x['Title'] + self.weight['body']*x['Body'] + self.weight['code']*x['Code']

        return x['text']

请注意,如果您未指定参数值,则默认情况下会传递它。这取决于你。然后,您可以通过执行以下操作来调用您的变压器:
textextractor = TextExtractor(weight = {'title' : 5, 'body': 2, 'code' : 1})
textextractor.transform(X)

这应该返回:
0    T1T1T1T1T1B1B1C1
1    T2T2T2T2T2B2B2C2
2    T3T3T3T3T3B3B3C3
3    T4T4T4T4T4B4B4C4
4    T5T5T5T5T5B5B5C5

然后,您可以定义参数网格:
param_grid = {
'vectorizer__min_df' : [0.1],
'vectorizer__max_df' : [0.9],
'vectorizer__max_features': [200],
# here is the parameter  I want to pass to my transformer
'textextractor__weight' : [{'title' : 10, 'body': 1, 'code' : 1}, {'title' : 1, 'body':
 1, 'code' : 1}]
}

最后做:
for g in ParameterGrid(param_grid) :

classifier_pipe = Pipeline(

steps=[    ('textextractor', TextExtractor(weight = g['textextractor__weight'])),
           ('vectorizer', TfidfVectorizer(max_df=g['vectorizer__max_df'],
                 min_df=g['vectorizer__min_df'], max_features=g['vectorizer__max_features'])),
           ('clf', sgd),  ] )

取而代之的是,您可能想要进行gridsearch,然后需要您编写:
pipe = Pipeline( steps=[    ('textextractor', TextExtractor()),
           ('vectorizer', TfidfVectorizer()),
           ('clf', sgd) ] )
grid = GridSearchCV(pipe, param_grid, cv = 3)
grid.fit(X,y)

关于scikit-learn - Sklearn管道: pass a parameter to a custom Transformer?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55142677/

10-11 07:38