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 的特徵工程