python - 在 sklearn Pipeline 中为每一列使用特定的 IterativeImputer
问题描述
我正在运行回归算法并使用 sklearn Pipelines 进行预处理。最初,我对所有数值列都使用了 Iterative Imputer,但我更愿意为某些列添加一些额外的步骤,因此对每个列或至少某些列使用不同的预处理步骤。在某些列中,零值是有效的,在其他列中,缺失值是如何标记的。
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor
import sklearn.preprocessing
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df_ml.iloc[:, :].drop(columns=['ClosePrice']),
df_ml.iloc[:, :]['ClosePrice'],
test_size=.33
)
tic = time.perf_counter()
cat_pipe = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent'))
])
# Define numerical pipeline
# IterativeImputer(estimator=ExtraTreesRegressor())
num_pipe = Pipeline([
('imputer', IterativeImputer(estimator=ExtraTreesRegressor(), missing_values=-1))
preprocessor = ColumnTransformer(transformers=[('cat', cat_pipe, categorical),
('num', num_pipe, numerical)
pipe = Pipeline(steps=[('preprocessor', preprocessor)])
#pipe.fit(X_train, y_train)
X_train_pre = pipe.fit_transform(X_train)
X_test_pre = pipe.fit_transform(X_test)
print(X_train_pre.shape, X_test_pre.shape)
此处的数字表示单个列,其中 -1 是缺失值指示符。当我运行这段代码时,所有缺失的值都会变成相同的值 - 6.77。
pd.DataFrame(X_train_pre).iloc[:, -1].value_counts().head()
6.000000 899
7.000000 823
8.000000 673
5.000000 671
6.772953 511
我可以看到这是因为 imputer 只考虑一列标记为数字的列并取平均值。如何使它考虑数据集中的所有列,尤其是目标变量?
更新:当我包含几列时,结果不再相同,但我仍然无法指定要添加哪些列,以便在为每个列使用特定管道时考虑到 imputer。
解决方案
推荐阅读
- c++ - Compiler error when implementing tree using queue (STL of C++)
- c# - 在 PuppeteerSharp 中评估 Fetch Api
- javascript - Block cookies from specific URLs?
- python - 如何从 python 脚本中运行 secretsdump.py?
- python - 无法在 Google App Engine 中使用 PostgreSQL 部署 Flask-Python 应用程序
- reactjs - 如何在 Typescript 中声明一个 React 组件扩展包组件?
- ocaml - Ocaml 记录和类型定义语法
- java - DFS Maze Solver 正确时返回 false
- python - Django smtplib.SMTPRecipientsRefused:收件人地址被拒绝:虚拟邮箱表中的用户未知
- batch-file - 批量输入第二次停止工作