【问题标题】:10 fold cross validation using logspline in R在 R 中使用对数样条进行 10 折交叉验证
【发布时间】:2014-02-20 07:38:21
【问题描述】:

我想做 10 折交叉验证,然后在 R 中使用 MSE 进行模型选择。我可以将数据分成10组,但出现以下错误,如何解决?

   crossvalind <- function(N, kfold) { 
              len.seg <- ceiling(N/kfold) 
              incomplete <- kfold*len.seg - N 
              complete <- kfold - incomplete 
              ind <- matrix(c(sample(1:N), rep(NA, incomplete)), nrow = len.seg, byrow = TRUE) 
              cvi <- lapply(as.data.frame(ind), function(x) c(na.omit(x))) # a list 
              return(cvi) 
   } 

我正在使用 logspline 包来估计密度函数。

  library(logspline)
  x = rnorm(300, 0, 1)
  kfold <- 10 
  cvi <- crossvalind(N = 300, kfold = 10) 
  for (i in 1:length(cvi)) { 
     xc <- x[cvi[-i]]    # x in training set 
     xt <- x[cvi[i]]    # x in test set 
     fit <- logspline(xc) 
     f.pred <- dlogspline(xt, fit)
     f.true <- dnorm(xt, 0, 1) 
     mse[i] <- mean((f.true - f.pred)^2)
 } 
 Error in x[cvi[-i]] : invalid subscript type 'list'

【问题讨论】:

    标签: r


    【解决方案1】:

    cvi 是一个列表对象,所以cvi[-1]cvi[1] 是列表对象,然后你尝试得到x[cvi[-1]],它使用列表对象进行下标,这没有意义,因为列表对象可以是包含数字、字符、日期和其他列表的复杂对象。

    用单方括号为列表下标总是返回一个列表。使用双方括号来获取成分,在这种情况下是向量。

    > cvi[1]  # this is a list with one element
    $V1
     [1] 101  78 231  82 211 239  20 201 294 276 181 168 207 240  61  72 267  75 218
    [20] 177 127 228  29 159 185 118 296  67  41 187
    
    > cvi[[1]] # a length 30 vector:
     [1] 101  78 231  82 211 239  20 201 294 276 181 168 207 240  61  72 267  75 218
    [20] 177 127 228  29 159 185 118 296  67  41 187
    

    这样你就可以得到x的那些元素:

    > x[cvi[[1]]]
     [1]  0.32751014 -1.13362827 -0.13286966  0.47774044 -0.63942372  0.37453378
     [7] -1.09954301 -0.52806368 -0.27923480 -0.43530831  1.09462984  0.38454106
    [13] -0.68283862 -1.23407793  1.60511404  0.93178122  0.47314510 -0.68034783
    [19]  2.13496564  1.20117869 -0.44558321 -0.94099782 -0.19366673  0.26640705
    [25] -0.96841548 -1.03443796  1.24849113  0.09258465 -0.32922472  0.83169736
    

    这不适用于负索引:

    > cvi[[-1]]
    Error in cvi[[-1]] : attempt to select more than one element
    

    所以不要用你不想要的列表元素下标x,而是用你想要的索引的负数下标(因为你在这里分区):

    > x[-cvi[[1]]]
    

    将返回其他 270 个元素。请注意,我在这里使用1 进行第一次循环,替换为i 并插入您的代码。

    【讨论】:

      猜你喜欢
      • 2014-09-16
      • 1970-01-01
      • 2012-11-01
      • 2011-11-29
      • 2023-02-24
      • 2020-02-10
      • 2013-08-16
      • 2012-05-11
      • 2021-06-03
      相关资源
      最近更新 更多