R 中的特征工程
Jorge Zazueta
Research Professor. Head of the Modeling Group at the School of Economics, UASLP
通过让数据更易处理,我们可以提升机器学习模型的性能。
glimpse(loans_num)
Rows: 614
Columns: 6
$ Loan_Status <fct> Y, N, Y, Y, Y, Y, Y, N, Y, N, Y, Y, Y, N...
$ ApplicantIncome <dbl> 5849, 4583, 3000, 2583, 6000, 5417, 233...
$ CoapplicantIncome <dbl> 0, 1508, 0, 2358, 0, 4196, 1516, 2504, 1...
$ LoanAmount <dbl> NA, 128, 66, 120, 141, 267, 95, 158, 168...
$ Loan_Amount_Term <dbl> 360, 360, 360, 360, 360, 360, 360, 360, ...
$ Credit_History <fct> 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1...
对数值特征做 log 变换可:
贷款金额的 log 变换数据

对数值特征进行归一化或缩放可:
例如,贷款期限数值差异很大

对数值特征进行归一化或缩放可:
归一化值保留分布,但仍有差异。

我们现在可以声明一个逻辑回归模型,并添加一个 recipe 来填补、归一化和对相关特征做对数变换。
lr_model <- logistic_reg()
lr_recipe <-
recipe(Loan_Status ~.,
data = train) %>%
step_impute_knn(
all_numeric_predictors())%>%
step_normalize(Loan_Amount_Term) %>%
step_log(all_numeric_predictors(),
-Loan_Amount_Term, offset = 1)
打印 recipe 对象会显示所应用步骤的摘要。
lr_recipe
Recipe
Inputs:
role #variables
outcome 1
predictor 5
Operations:
K-nearest neighbor imputation for all_numeric_predictors()
Centering and scaling for Loan_Amount_Term
Log transformation on all_numeric_predictors(),-Loan_Amount_Term
我们定义一组指标 roc_auc、accuracy 和 sens 来评估拟合的工作流对象 lr_fit。
class_evaluate <- metric_set(
roc_auc, accuracy, sens)
然后像调用普通函数一样运行。
lr_aug %>%
class_evaluate(
truth = Loan_Status,
estimate = .pred_class,
.pred_Y)
自定义指标集
# A tibble: 3 × 3
.metric .estimator .estimate
<chr> <chr> <dbl>
1 accuracy binary 0.813
2 sens binary 0.467
3 roc_auc binary 0.288
R 中的特征工程