因此,我使用“scikit-learn”在训练集上构建机器学习模型,然后在测试集上对其进行评估。在训练集上,我使用
ColumnTransformer
执行数据插补和缩放,然后使用 Kfold CV 构建逻辑回归模型,最终模型用于预测测试集上的值。最终模型还使用 ColumnTransformer
的结果来估算测试集上的缺失值,例如,最小-最大标量将从训练集中获取最小值和最大值,并在缩放测试集时使用这些值。如何查看从训练集导出的这些缩放值,然后用于在测试集上进行预测?我在“scikit-learn”文档中找不到任何相关内容。这是我正在使用的代码:
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.model_selection import GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
def preprocessClassifierLR(categorical_vars, numeric_vars):###categorical_vars and numeric_vars are lists defining the column names of the categorical and numeric variables present in X
categorical_pipeline = Pipeline(steps=[('mode', SimpleImputer(missing_values=np.nan, strategy="most_frequent")),
("one_hot_encode", OneHotEncoder(handle_unknown='ignore'))])
numeric_pipeline = Pipeline(steps=[('numeric', SimpleImputer(strategy="median")),
("scaling", MinMaxScaler())])
col_transform = ColumnTransformer(transformers=[("cats", categorical_pipeline, categorical_vars),
("nums", numeric_pipeline, numeric_vars)])
lr = SGDClassifier(loss='log_loss', penalty='elasticnet')
model_pipeline = Pipeline(steps=[('preprocess', col_transform),
('classifier', lr)])
random_grid_lr = {'classifier__alpha': [1e-1, 0.2, 0.5],
'classifier__l1_ratio': [1e-3, 0.5]}
kfold = RepeatedStratifiedKFold(n_splits=10, n_repeats=10, random_state=47)
param_search = GridSearchCV(model_pipeline, random_grid_lr, scoring='roc_auc', cv=kfold, refit=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
param_search = preprocessClassifierLR(categorical_vars, numeric_vars)
train_mod = param_search.fit(X_train, y_train)
print("Mod AUC:", train_mod.best_score_)
test_preds = train_mod.predict_proba(X_)[:,1]
我无法提供真实数据,但 X 是具有自变量的数据框,y 是二进制结果变量。 train_mod 是一个管道,其中包含列转换器和 SGD 分类器步骤。我可以轻松地从分类器中获取类似的参数信息,例如通过运行:
train_mod.best_params_
来获得最佳 lambda 和 alpha 值,但我无法弄清楚用于列转换器的统计数据,例如 1)用于简单输入器的模式分类特征,2) 用于数字特征的简单输入器的中值,以及 3) 用于数字特征缩放的最小值和最大值。有谁知道如何访问这些信息?
预先感谢!
我假设
train_mod.best_estimator_['preprocess'].transformers_
将包含此信息,类似于 train_mod.best_params_
为我提供从模型训练中得出的 alpha 和 lambda 值,然后将其应用于测试集。
Pipelines、ColumnTransformers、GridSearch 等都具有暴露其组件部分的属性(有时还有自定义
__getitem__
来访问这些属性,如字典),并且类似地,每个转换器都将统计数据作为属性,因此这只是链接的问题这些都在一起,例如:
(
train_mod # is a grid search, has the next attribute
.best_estimator_ # is a pipeline, has steps accessible by getitem
['preprocess'] # is a columntransformer
.named_transformers_ # fitted transformers, accessed by getitem
['cats'] # pipeline
['mode'] # simpleimputer
.statistics_ # the computed modes, per column seen by this simpleimputer.
)