【发布时间】:2022-03-29 17:45:22
【问题描述】:
我正在运行回归算法并使用 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
我可以看到这是因为估算器只考虑标记为数字的一列并取平均值。如何使它考虑数据集中的所有列,尤其是目标变量?
更新:当我包含多个列时,结果不再相同,但我仍然无法指定在为每个列使用特定管道时要添加哪些列以供估算器考虑。
【问题讨论】:
标签: python python-3.x machine-learning scikit-learn imputation