You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言线性回归建模及vfold_cv函数使用问题求助

问题解答

1. 解决prep函数找不到的错误

出现could not find function "prep"是因为你没加载recipes包,另外代码里用到的initial_split、vfold_cv来自rsample包,linear_reg来自parsnip包,step_smote来自themis包——这些都属于tidymodels工具集,先把必要的包装上并加载:

# 加载所需包
library(tidyverse)   # 包含read_csv等常用数据处理函数
library(tidymodels)  # 整合rsample、parsnip、recipes等建模工具
library(themis)      # 提供step_smote函数(注意:回归任务用不上这个,后面会说明)

另外你手动把字符转成因子的步骤可以删掉,recipe里的step_string2factor能自动完成这个操作,更省心。

2. 正确使用vfold_cv做交叉验证

在tidymodels工作流里,交叉验证需要结合数据预处理规则(recipe)、模型定义、工作流(整合两者),用fit_resamples在折叠上训练并评估模型,步骤如下:

完整修正后的代码示例

# 1. 加载包
library(tidyverse)
library(tidymodels)
library(themis)

# 2. 读取数据
AirBnB_price <- read_csv('train_2.csv')

# 3. 划分训练/测试集(设置随机种子保证结果可复现)
set.seed(123)
AirBnB_price_split <- initial_split(AirBnB_price, prop = 0.8)
AirBnB_price_train <- training(AirBnB_price_split)
AirBnB_price_test <- testing(AirBnB_price_split)

# 4. 创建交叉验证折叠(基于训练集,用10折分层验证)
set.seed(456)
cv_folds <- vfold_cv(AirBnB_price_train, strata = price, v = 10)

# 5. 定义预处理规则(注意:step_smote是分类任务用的,回归任务请删除这一行)
AirBnB_recipe <- recipe(price ~ ., data = AirBnB_price_train) %>%
  update_role(host_id, new_role = "Id") %>%
  step_string2factor(neighbourhood, neighbourhood_group, room_type) %>%
  step_other(neighbourhood, threshold = 0.01) %>%  # 合并低频社区类别
  step_dummy(all_nominal_predictors()) %>%  # 对分类变量做哑变量编码
  step_zv(all_predictors()) %>%  # 移除零方差无意义变量
  step_normalize(all_numeric_predictors()) %>%  # 标准化数值变量
  # step_smote(price)  # 回归任务不需要此步骤,建议删除
  prep()  # 直接在recipe里完成预处理训练,不用单独调用prep函数

# 6. 定义线性回归模型
lm_spec <- linear_reg() %>%
  set_engine("lm") %>%
  set_mode("regression")  # 明确是回归预测任务

# 7. 创建工作流(整合预处理和模型)
lm_workflow <- workflow() %>%
  add_recipe(AirBnB_recipe) %>%
  add_model(lm_spec)

# 8. 在交叉验证折叠上训练并评估模型
cv_results <- fit_resamples(
  object = lm_workflow,
  resamples = cv_folds,
  metrics = metric_set(rsq, rmse, mae)  # 选择回归任务的评估指标:决定系数、均方根误差、平均绝对误差
)

# 查看交叉验证结果
collect_metrics(cv_results)

# 9. 在完整训练集上训练最终模型,并用测试集评估
final_fit <- last_fit(lm_workflow, AirBnB_price_split)
collect_metrics(final_fit)
# 可视化预测值和真实值的关系
collect_predictions(final_fit) %>% 
  ggplot(aes(x = price, y = .pred)) + 
  geom_point(alpha = 0.3) + 
  geom_abline(color = "red")

关键说明

  • 交叉验证的位置:必须在划分训练/测试集之后,基于训练集创建折叠,保证测试集完全独立,避免数据泄露。
  • 为什么用workflow:它会自动在每个交叉验证折叠内单独执行预处理,避免在整个训练集上预处理再拆分导致的泄露问题,同时减少重复代码。
  • 关于step_smote:这个函数是用来处理分类任务的类别不平衡问题的,你的任务是预测连续的price(回归任务),完全不需要这个步骤,保留会报错或无效。

内容的提问来源于stack exchange,提问作者Preksha Rathore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:10:20