R 中的特征工程
Jorge Zazueta
Research Professor and Head of the Modeling Group at the School of Economics, UASLP
有些数据集包含常量列或零方差列。可在 recipe() 中添加 step_zv() 过滤此类特征。

近零方差特征包括仅取单一值的预测变量,及同时满足以下两点的预测变量:
相较样本数,唯一值很少
最常见值与第二常见值的频率比值很大
近零方差示例:
step_nzv() 可识别并移除具备这些特征的预测变量。
原始三维数据集,含两个类别。

降维后,用前两个主成分表示的数据集。

创建执行 PCA 的 recipe,并用 prep() 获取输出。
pc_recipe <-
recipe(~., data = loans_num) %>%
step_nzv(all_numeric()) %>%
step_normalize(all_numeric()) %>%
step_pca(all_numeric())
pca_output <- prep(pc_recipe)
可通过对 pca_output 调用 names() 查看可用信息。
names(pca_output)
[1] "var_info" "term_info"
[3] "steps" "template"
[5] "levels" "retained"
[7] "requirements" "tr_info"
[9] "orig_lvls" "last_term_info"
从 pca_output 对象提取标准差并计算解释方差。
stdv <- pca_output$steps[[3]]$res$sdev
var_explained <- stdv^2/sum(stdv^2)
PCA = tibble(PC = 1:length(stdv),
var_explained = var_explained,
cumulative = cumsum(var_explained))
按主成分给出的解释方差表。
# A tibble: 5 × 3
PC var_explained cumulative
<int> <dbl> <dbl>
1 1 0.315 0.315
2 2 0.214 0.529
3 3 0.202 0.730
4 4 0.198 0.928
5 5 0.0722 1
可用 ggplot2 将结果绘制为柱状图。
PCA %>%
ggplot(aes(x = PC,
y = var_explained)) +
geom_col(fill = "steelblue") +
xlab("Principal components") +
ylab("Variance explained")
主成分的解释方差。

R 中的特征工程