24小时热门版块排行榜    

查看: 1920  |  回复: 4
本帖产生 1 个 计算强帖 ,点击这里进行查看
当前只显示满足指定条件的回帖,点击这里查看本话题的所有回帖

snoopyzhao

至尊木虫 (职业作家)

★ ★ ★ ★ ★
luoqiquan(金币+5, 计算强帖+1):thank you very much 2010-11-05 20:30:43
贴一个我用 R 语言写的 LOO-LGO CV 的程序,应该能够看得懂,至于其它语言如何实现,我就无能为力了……
CODE:
lmcv <- function(obj, ng = NULL, random = FALSE) {
#
# The Leave-One-Out (LOO) and/or Leave-Group-Out (LGO) Cross-Validation in R for (Multiple) Linear Regression.
#
# Input:
#   obj: the model of MLR
#   ng: number of group, if missing, do LOO
#   random: logical, if TRUE, do random CV
#
# Output:
#   q.squared: cross-validation relation coefficient.
#   SDEP: Standard Deviation of Error of Predictions
#   newsq: variance in Y explained only for LOO CV
#
# Usage:
#   loo <- cv.lm(obj)
#   lgo <- cv.lm(obj, ng = 5)
#
    data <- data.frame(y = obj$model[,1], x = obj$model[, -1])
    col.names <- colnames(data)
    N <- nrow(data)
    if (random == TRUE) data <- data[sample(1:N),]
    if (missing(ng)) ng <- N # LOO CV
    ytest <- numeric(N)
    ypred <- numeric(N)
    newrsq <- numeric(ng)
    g <- N %/% ng
    for (i in 1:ng) {
        if (g == 1) {
            index <- i
        }
        else {
            index <- c(i, ng * seq(1, (g - 1)) + i)
            if (N %% ng != 0 & i <= N %% ng) index <- c(index, (g * ng + i))
        }
        ytest[index] <- data[index,1]
        newtrain <- data[-index, ]
        xtest <- data.frame(x = data[index, -1])
        colnames(xtest) <- col.names[-1]
        newfm <- lm(y ~., data = newtrain)
        newrsq[i] <- summary(newfm)$r.squared
        ypred[index] <- predict(newfm, xtest)
    }
    q.squared <- 1 - sum((ytest - ypred)^2) / sum((ytest - mean(ytest))^2)
    SDEP <- sqrt(sum((ytest - ypred)^2) / N)
    return(list(q.squared = q.squared, SDEP = SDEP, newrsq = newrsq))
}

3楼2010-11-05 20:09:14
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

智能机器人

Robot (super robot)

我们都爱小木虫

找到一些相关的精华帖子,希望有用哦~

科研从小木虫开始,人人为我,我为人人
相关版块跳转 我要订阅楼主 songbin7957 的主题更新
普通表情 高级回复 (可上传附件)
信息提示
请填处理意见