我已经建立了一个自定义的sklearn管道,如下所示:
我遇到了 `AttributeError: module '__main__' has no attribute 'SelectColumnsTransfomer'` 错误。
我已经阅读了其他类似的问题,并按照这篇博客文章 here 中的说明进行操作,但是无法解决问题。我正在复制并粘贴类,并在代码中导入它们。如果我创建这个练习的简化版本,整个过程都可以正常工作,问题出现在我使用 pytest 进行一些测试时,当我运行 pytest 时,它似乎看不到我的自定义类,实际上还有错误的另一部分
我的测试代码:
pipeline = make_pipeline(
SelectColumnsTransfomer(features_to_use),
ToDummiesTransformer('feature_0', prefix='feat_0', drop_first=True, dtype=bool), # Dummify customer_type
ToDummiesTransformer('feature_1', prefix='feat_1'), # Dummify the feature
ToDummiesTransformer('feature_2', prefix='feat_2'), # Dummify
ToDummiesTransformer('feature_3', prefix='feat_3'), # Dummify
)
pipeline.fit(df)
类SelectColumnsTransfomer
和ToDummiesTransformer
是自定义的sklearn步骤,实现了BaseEstimator
和TransformerMixin
。
为了序列化这个对象,我使用
from sklearn.externals import joblib
joblib.dump(pipeline, 'data_pipeline.joblib')
但是当我使用反序列化时
pipeline = joblib.load('data_pipeline.joblib')
我遇到了 `AttributeError: module '__main__' has no attribute 'SelectColumnsTransfomer'` 错误。
我已经阅读了其他类似的问题,并按照这篇博客文章 here 中的说明进行操作,但是无法解决问题。我正在复制并粘贴类,并在代码中导入它们。如果我创建这个练习的简化版本,整个过程都可以正常工作,问题出现在我使用 pytest 进行一些测试时,当我运行 pytest 时,它似乎看不到我的自定义类,实际上还有错误的另一部分
self = <sklearn.externals.joblib.numpy_pickle.NumpyUnpickler object at 0x7f821508a588>, module = '__main__', name = 'SelectColumnsTransfomer'
,这提示我 NumpyUnpickler
看不到 SelectColumnsTransfomer
,即使在测试中已经导入了它。我的测试代码:
import pytest
from app.pipeline import * # the pipeline objects
# SelectColumnsTransfomer and ToDummiesTransformer
# are here!
@pytest.fixture(scope="module")
def clf():
pipeline = joblib.load("persistence/data_pipeline.joblib")
return clf
def test_fake(clf):
assert True