r - 在R中,在tidymodels的配方中选择X个第一个PCA组件
问题描述
我想在配方中计算出第 X 个 PCA 组件后选择它们。然后我想在工作流程中添加这个配方。
请参阅下面的示例数据。
library(tidymodels)
x1 <- c(1, 6, 4, 2, 3, 4, 5, 7, 8, 2)
x2 <- c(1, 3, 4, 2, 3, 4, 5, 7, 8, 2)
x3 <- c(1, 3, 4, 2, 3, 4, 5, 7, 8, 2)
x4 <- c(1, 3, 4, 2, 3, 4, 5, 7, 8, 2)
id <- c(1:10)
y <- c(1, 4, 2, 5, 6, 2, 3, 6, 2, 4)
df1_train <- tibble(x1, x2, x3, x4, id, y)
step_PCA_PREPROCESSING = 4
selectXfirstPCA = 3
# My recipe
df1_train_recipe <- df1_train %>%
recipes::recipe(y ~ .) %>%
recipes::update_role(id, new_role = "id variable") %>%
recipes::step_pca(., recipes::all_predictors(), num_comp = step_PCA_PREPROCESSING) %>%
recipes::update_role(tidyselect::num_range("PC", 1:selectXfirstPCA), new_role = "predictor")
# To then continue like below:
# Model specifications
model_spec <- parsnip::linear_reg() %>%
parsnip::set_engine("glmnet")
# Create workflow (to know variable roles from recipes)
df1_workflow <- workflows::workflow() %>%
workflows::add_recipe(df1_train_recipe) %>%
workflows::add_model(model_spec)
# Fit model
mod <- parsnip::fit(df1_workflow, data = df1_train)
解决方案
这只是num_comp
. step_pca()
根据文档,num_comp
是“作为新预测变量保留的 PCA 组件的数量。如果 num_comp 大于列数或可能组件的数量,将使用较小的值。”
所以你的代码可以简单地
recipes::step_pca(., recipes::all_predictors(), num_comp = selectXfirstPCA)
删除最后update_role()
一行。
推荐阅读
- angular - 角材料自动完成不显示列表框的选项
- jsf - p:commandButton doesn't dislpay p:dialog
- python-3.x - 从具有明确前缀但随机后缀的 Cloud Storage 读取文件
- powershell - 尝试使用嵌套引号从 PowerShell 运行 sc create 并且无法使其工作
- python-3.x - 不了解 sklearn 的 HashingVectorizer
- node.js - 使用 nodejs 以编程方式定义表模式
- sql - 如何针对滚动的 1 小时窗口汇总结果
- c# - 检查用户是否添加到应用程序
- angularjs - 如何混淆cordova项目的www文件夹中的angularjs代码?
- awk - 如何将文件的第n行重复m次