TypeError: ‘Pipeline’ 对象不可调用的自定义分类器

我正在处理一个分类问题。我为我的分类器创建了一个类。我在这个类上遇到了一个问题。我有一个 get_clf_pipeline 方法,它返回分类器管道,该管道由 train 方法使用。这个方法不需要访问实例或类数据,我尝试将其设为静态方法,但这种方法也不奏效。我该如何解决这个问题?

class Event_classifier:
    def __init__(self):
        self.clf_pipeline = self.get_clf_pipeline()

    def get_clf_pipeline(self):
        """ 返回管道 """
        categorical_features = ['CRole', 'Clevel', 'Gender']
        categorical_transformer = Pipeline(steps=[
            ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
            ('onehot', OneHotEncoder(handle_unknown='ignore'))])
        preprocessor = ColumnTransformer(
            transformers=[
                ('cat', categorical_transformer, categorical_features)])
        estimators = [
            ('rf',RandomForestClassifier(n_estimators=200,class_weight='balanced')),
            ('mnb', MultinomialNB()),
            ('svr', make_pipeline(StandardScaler(with_mean=False),
                                 LinearSVC(random_state=42)))
        ]
        stacked_clf = StackingClassifier(
             estimators=estimators, final_estimator=LogisticRegression(class_weight='balanced')
        )
        clf_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
                                       ('classifier', stacked_clf)])
        return clf_pipeline

    def train(self, X,y):
        """ 在输入数据上训练分类器 """
        print(type(self.clf_pipeline))
        self.clf_pipeline(X,y)

    def predict(self):
        """ 在测试数据上进行预测 """
        if (X.shape) == 1:
            X = X.T
        y_pred = self.clf_pipeline.predict(X)
        return y_pred

创建类实例并在数据上进行训练

ec = Event_classifier()
ec.train(X_train, y_train)
print('模型训练完成')

我得到了以下错误

<class 'sklearn.pipeline.Pipeline'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-129-36d8dfcdfc12> in <module>
      1 ec = Event_classifier()
      2 ----> 3 ec.train(X_train, y_train)
      4 print('模型训练完成')
      5 
<ipython-input-126-de5f651c0a3d> in train(self, X, y)
     35         """
     36         print(type(self.clf_pipeline))
---> 37         self.clf_pipeline(X,y)
     38 
     39     def predict(self):
TypeError: 'Pipeline' object is not callable

回答:

你的 self.clf_pipeline 是一个 Pipeline 对象,因此 self.clf_pipeline(X,y) 试图在输入 X, y 上调用管道,但(正如错误所说)Pipeline 不是函数。可能你想要的是 self.clf_pipeline.fit(X, y)

还有一点引人注目:在你的 predict 方法中,什么时候 X.shape == 1

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注