如果我运行以下 Python 代码,它运行良好:
target = 'churn'
tranOH = ColumnTransformer([ ('one', OneHotEncoder(drop='first', dtype='int'),
make_column_selector(dtype_include='category', pattern=f"^(?!{target}).*")
) ], remainder='passthrough')
dftrain2 = tranOH.fit_transform(dftrain)
cph = CoxPHFitter(penalizer=0.1)
cph.fit(dftrain2, 'months', 'churn')
但是如果我尝试使用管道执行此操作,则会收到错误:
mcox = Pipeline(steps=[
("onehot", tranOH),
('modelo', CoxPHFitter(penalizer=0.1))
])
mcox.fit(dftrain, modelo__duration_col="months", modelo__event_col='churn')
它说:
TypeError Traceback (most recent call last)
Cell In[88], line 6
1 mcox = Pipeline(steps=[
2 ("onehot", tranOH),
3 ('modelo', CoxPHFitter(penalizer=0.1))
4 ])
----> 6 mcox.fit(dftrain, modelo__duration_col="months", modelo__event_col=target)
File ~\AppData\Roaming\Python\Python310\site-packages\sklearn\base.py:1473, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
1466 estimator._validate_params()
1468 with config_context(
1469 skip_parameter_validation=(
1470 prefer_skip_nested_validation or global_skip_validation
1471 )
1472 ):
-> 1473 return fit_method(estimator, *args, **kwargs)
File ~\AppData\Roaming\Python\Python310\site-packages\sklearn\pipeline.py:473, in Pipeline.fit(self, X, y, **params)
471 if self._final_estimator != "passthrough":
472 last_step_params = routed_params[self.steps[-1][0]]
--> 473 self._final_estimator.fit(Xt, y, **last_step_params["fit"])
475 return self
File ~\AppData\Roaming\Python\Python310\site-packages\lifelines\utils\__init__.py:56, in CensoringType.right_censoring.<locals>.f(model, *args, **kwargs)
53 @wraps(function)
54 def f(model, *args, **kwargs):
55 cls.set_censoring_type(model, cls.RIGHT)
---> 56 return function(model, *args, **kwargs)
TypeError: CoxPHFitter.fit() got multiple values for argument 'duration_col'
tranOH 是一个列转换器,onehot 对除“churn”之外的所有分类列进行编码。
我也尝试过直接在
col="months"
内部使用event_col=target
和CoxPHFitter()
,但我得到了同样的错误。
后来我想用它来执行 GridSearchCV 来微调惩罚器参数,优化准确度分数以预测给定时间=“月”的流失率。
我对其他模型没有同样的问题,例如,如果我用 LogisticRegression 替换 CoxPHFitter,它效果很好。
CoxPHFitter
不遵守 sklearn API:它的 fit
方法采用 df
后跟其他参数(先是 duration_col
),而不是 X
然后 y
后跟其他参数。
这基本上没问题,因为您可以将整个帧(包括目标和持续时间列)作为
X
传递,sklearn 管道只会将其视为无监督设置,即默认值 y=None
。 但是,然后我们开始拟合管道的最后一步,这被称为:
self._final_estimator.fit(Xt, y, **last_step_params["fit"])
(来源)。 这里的
y
仍然是 None
,但是由于 CoxPHFitter
将其第二个参数视为 duration_col
,这意味着同时设置为 None
(通过此处的 y
参数)然后设置为 "months"
(你的 kwarg 参数)。
我认为没有简单的方法可以解决这个问题。
lifelines
提供了 sklearn_wrapper
,但这似乎有其自身的问题,预计将在 0.28 版本中删除。 我只是将模型与预处理管道分开。