【发布时间】:2018-01-02 06:46:20
【问题描述】:
我正在尝试根据本教程的指导为 Python sklearn 管道创建一个自定义转换器:http://danielhnyk.cz/creating-your-own-estimator-scikit-learn/
现在我的自定义类/变压器看起来像这样:
class SelectBestPercFeats(BaseEstimator, TransformerMixin):
def __init__(self, model=RandomForestRegressor(), percent=0.8,
random_state=52):
self.model = model
self.percent = percent
self.random_state = random_state
def fit(self, X, y, **fit_params):
"""
Find features with best predictive power for the model, and
have cumulative importance value less than self.percent
"""
# Check parameters
if not isinstance(self.percent, float):
print("SelectBestPercFeats.percent is not a float, it should be...")
elif not isinstance(self.random_state, int):
print("SelectBestPercFeats.random_state is not a int, it should be...")
# If checks are good proceed with fitting...
else:
try:
self.model.fit(X, y)
except:
print("Error fitting model inside SelectBestPercFeats object")
return self
# Get feature importance
try:
feat_imp = list(self.model.feature_importances_)
feat_imp_cum = pd.Series(feat_imp, index=X.columns) \
.sort_values(ascending=False).cumsum()
# Get features whose cumulative importance is <= `percent`
n_feats = len(feat_imp_cum[feat_imp_cum <= self.percent].index) + 1
self.bestcolumns_ = list(feat_imp_cum.index)[:n_feats]
except:
print ("ERROR: SelectBestPercFeats can only be used with models with"\
" .feature_importances_ parameter")
return self
def transform(self, X, y=None, **fit_params):
"""
Filter out only the important features (based on percent threshold)
for the model supplied.
:param X: Dataframe with features to be down selected
"""
if self.bestcolumns_ is None:
print("Must call fit function on SelectBestPercFeats object before transforming")
else:
return X[self.bestcolumns_]
我正在将这个类集成到这样的 sklearn 管道中:
# Define feature selection and model pipeline components
rf_simp = RandomForestRegressor(criterion='mse', n_jobs=-1,
n_estimators=600)
bestfeat = SelectBestPercFeats(rf_simp, feat_perc)
rf = RandomForestRegressor(n_jobs=-1,
criterion='mse',
n_estimators=200,
max_features=0.4,
)
# Build Pipeline
master_model = Pipeline([('feat_sel', bestfeat), ('rf', rf)])
# define GridSearchCV parameter space to search,
# only listing one parameter to simplify troubleshooting
param_grid = {
'feat_select__percent': [0.8],
}
# Fit pipeline model
grid = GridSearchCV(master_model, cv=3, n_jobs=-1,
param_grid=param_grid)
# Search grid using CV, and get the best estimator
grid.fit(X_train, y_train)
每当我运行最后一行代码 (grid.fit(X_train, y_train)) 时,我都会收到以下“PicklingError”。谁能在我的代码中看到导致此问题的原因?
编辑:
或者,我的 Python 设置中是否有问题……我可能缺少一个包或类似的东西吗?我刚刚检查了我可以成功import pickle
Traceback(最近一次调用最后一次):文件“”,第 5 行,in 文件 "C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\model_selection_search.py", 第 945 行,合适 返回 self._fit(X, y, groups, ParameterGrid(self.param_grid)) 文件 "C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\model_selection_search.py", 第 564 行,在 _fit 对于 parameter_iterable 文件“C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\externals\joblib\parallel.py”中的参数, 第 768 行,在 调用 self.retrieve() 文件 "C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\externals\joblib\parallel.py", 第 719 行,在检索中 引发异常文件“C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\externals\joblib\parallel.py”, 第 682 行,在检索中 self._output.extend(job.get(timeout=self.timeout)) 文件 "C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\multiprocessing\pool.py", 第 608 行,在获取 提高 self._value 文件“C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\multiprocessing\pool.py”, 第 385 行,在 _handle_tasks 中 放置(任务)文件“C:\Users\jjaaae\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\externals\joblib\pool.py”, 第 371 行,在发送中 CustomizablePickler(buffer, self._reducers).dump(obj) _pickle.PicklingError: Can't pickle : 属性查找 SelectBestPercFeats on builtins 失败
【问题讨论】:
-
或者,我的 Python 设置中是否有问题……我可能缺少一个包或类似的东西吗?我刚刚检查了我可以成功
import pickle。 -
我想我明白了。 pickle 包需要定义要在另一个模块中定义并导入的自定义类。所以我创建了另一个名为 transformation.py 的文件,然后像
from transformation import SelectBestPercFeats一样将其导入。这解决了酸洗错误 -
还要确保您可以取消保存已保存的估算器并按预期工作。
-
@VivekKumar,感谢您的提醒。我检查了一下,一切都很好。但是,根据我的经验,情况并非总是如此,因此我很感激您的提醒。
标签: python scikit-learn pickle pipeline neuraxle