如何让R中的Forward Selection逐步回归返回非仅截距的模型?
向前逐步回归仅返回截距的问题
我正在对比新型自动化最优模型选择技术与LASSO、向后逐步回归两种基准方法的特性。此前已在蒙特卡洛模拟所用的47501个合成数据集上成功迭代运行LASSO和向后逐步回归,出于好奇尝试运行向前逐步回归,但每个数据集拟合的模型都仅包含截距。
成功运行的向后逐步回归代码
directory_path <- "~/DAEN_698/other datasets/sample_obs2" filepath_list <- list.files(path = directory_path, full.names = TRUE, recursive = TRUE) # reformat the names of each of the csv file formatted datasets DS_names_list <- basename(filepath_list) DS_names_list <- tools::file_path_sans_ext(DS_names_list) ## This line reads all of the data in each of the csv files ## using the name of each store in the list we just created. datasets <- lapply(list.files(path = "~/DAEN_698/other datasets/sample_obs2", full.names = TRUE, recursive = TRUE), read.csv) ### Step 3: Run a Backward Elimination Stepwise Regression ### function on each of the 47,500 datasets. set.seed(11) # for reproducibility full_model <- vector("list", length = length(datasets)) BE_fits <- vector("list", length = length(datasets)) BE_fits # returns a list with 15 elements, all of which are NULL set.seed(11) # for reproducibility for(i in seq_along(datasets)) { full_model[[i]] <- lm(formula = Y ~ ., data = datasets[[i]]) BE_fits[[i]] <- step(object = full_model[[i]], scope = formula(full_model[[i]]), direction = 'backward', trace = 0) }
尝试的向前逐步回归代码
### Step 4/5 (optional): Run a Forward Selection Stepwise Regression ### function on each of the 47,500 datasets. ### Assign the null models to their corresponding datasets and ### store these in the object "null_models" set.seed(11) # for reproducibility #datasets[[1]]$ # try this line below if the line of code after it does not run/work #null_model = lm(datasets[[1]]$Y ~ 1, data = datasets) null_models <- vector("list", length = length(datasets)) FS_fits <- vector("list", length = length(datasets)) FS_fits # returns a list with 15 elements, all of which are NULL set.seed(11) # for reproducibility for(j in seq_along(datasets)) { null_models[[j]] <- lm(formula = Y ~ 1, data = datasets[[j]]) FS_fits[[j]] <- step(object = null_models[[j]], scope = formula(null_models[[j]]), direction = 'forward', trace = 0) }
运行结果
> head(null_models, n = 1) [[1]] Call: lm(formula = Y ~ 1, data = datasets[[j]]) Coefficients: (Intercept) 1.017 > head(FS_fits, n = 1) [[1]] Call: lm(formula = Y ~ 1, data = datasets[[j]]) Coefficients: (Intercept) 1.017 > names(coef(FS_fits[[1]])) [1] "(Intercept)" > names(coef(FS_fits[[2]])) [1] "(Intercept)" > names(coef(FS_fits[[3]])) [1] "(Intercept)"
内容的提问来源于stack exchange,提问作者Marlen
相关产品推荐
相关产品推荐

