如何在R中使用CAST包处理多边形Shapefile并运行Lasso模型?
问题描述
目标:针对sf多边形格式的数据运行LASSO模型进行变量选择。
数据:带多边形的shapefile,为sf对象。
尝试使用ffs或train函数均无法正常运行,以下是可复现示例(忽略变量名中74和79结尾的时间关联):
library(sf) library(CAST) # 加载数据 nc <- st_read(system.file("shape/nc.shp", package="sf")) # 划分训练集和测试集 set.seed(100) ind <- sample(2,nrow(nc),replace=T,prob = c(0.7,0.3)) train <- nc[ind==1,] test <- nc[ind==2,] predictors <- c("SID74","BIR79","BIR74") response <- "NWBIR79"
尝试1:使用ffs进行前向特征选择
set.seed(10) ffs(train[,predictors], train$NWBIR79,method = "lasso")
报错信息:
[1] "model using SID74,BIR79 will be trained now..." Something is wrong; all the RMSE metric values are missing: RMSE Rsquared MAE Min. : NA Min. : NA Min. : NA 1st Qu.: NA 1st Qu.: NA 1st Qu.: NA Median : NA Median : NA Median : NA Mean :NaN Mean :NaN Mean :NaN 3rd Qu.: NA 3rd Qu.: NA 3rd Qu.: NA Max. : NA Max. : NA Max. : NA NA's :3 NA's :3 NA's :3 Error: Stopping In addition: There were 26 warnings (use warnings() to see them)
尝试2:直接使用train训练LASSO模型
set.seed(100) model <- train(train[,predictors], train$NWBIR79, method="lasso", trControl=trainControl(method = "cv"),importance=T)
报错信息:
Something is wrong; all the RMSE metric values are missing: RMSE Rsquared MAE Min. : NA Min. : NA Min. : NA 1st Qu.: NA 1st Qu.: NA 1st Qu.: NA Median : NA Median : NA Median : NA Mean :NaN Mean :NaN Mean :NaN 3rd Qu.: NA 3rd Qu.: NA 3rd Qu.: NA Max. : NA Max. : NA Max. : NA NA's :3 NA's :3 NA's :3 Error: Stopping In addition: There were 11 warnings (use warnings() to see them)
解决方案
报错核心原因是传入的是包含几何列的sf对象,train(caret包)和ffs(CAST包)无法直接处理带空间几何信息的sf对象,必须先移除几何列,仅保留属性数据。
修改步骤与代码示例
- 先从训练集的sf对象中移除几何列,转换为普通数据框:
# 提取需要的属性列并移除几何信息 train_attr <- st_drop_geometry(train[, c(predictors, response)]) # 分离预测变量和响应变量 x_train <- train_attr[, predictors] y_train <- train_attr[[response]]
- 修改后的ffs运行代码:
set.seed(10) ffs_model <- ffs(x_train, y_train, method = "lasso")
- 修改后的train运行代码:
set.seed(100) model <- train(x_train, y_train, method="lasso", trControl=trainControl(method = "cv"), importance=T)
这样处理后,函数就能正常处理纯数值的属性数据,不会因几何列的存在导致计算错误。
内容的提问来源于stack exchange,提问作者Adriana Castillo Castillo
相关产品推荐
相关产品推荐

