对象“i”在 R for 循环中未找到(k 折交叉验证)

发布于 2025-01-21 03:23:50 字数 468 浏览 2 评论 0原文

就像标题所说的那样,我正在尝试进行K-折叠的交叉验证。我的编码技巧非常基本,请尽可能简单地解释。

    library(ISLR)
    install.packages("ISLR")
    library(ISLR)
    install.packages("boot")
    library(boot)

    data <- attach(read.csv("TutWk7Data-1.csv",header=TRUE))

    MSE = NULL

    for (i in 1:7){
      model = glm(Y~poly(X,i),data=data)
      MSE[i] = cv.glm(data,model,K=10)$delta[1]
    }

我有这个错误

Error in poly(X,i):object "i" not found

Like the title says, I am trying to do k-fold cross validation. My coding skills are very basic, please explain as simply as possible.

    library(ISLR)
    install.packages("ISLR")
    library(ISLR)
    install.packages("boot")
    library(boot)

    data <- attach(read.csv("TutWk7Data-1.csv",header=TRUE))

    MSE = NULL

    for (i in 1:7){
      model = glm(Y~poly(X,i),data=data)
      MSE[i] = cv.glm(data,model,K=10)$delta[1]
    }

I get this error

Error in poly(X,i):object "i" not found

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尝蛊 2025-01-28 03:23:50

问题是由于您使用 attach 引起的。根据 attach 的帮助页面,

环境通过“name”属性以不可见的方式返回。

您将该环境存储在 data 对象中。另一方面,cv.glm 的帮助页面指出“data”参数必须是“包含数据的矩阵或数据框”。您可以在运行时检查这一点:

> inherits(data, "data.frame")
[1] FALSE

因为 data 不是数据帧(即使它的行为非常像数据帧!),所以当您将其传递给 cv 时,所有的赌注都将消失.glm.

正如评论者所说,删除 attach 调用:它是多余的(并且无论如何都有看不见的副作用)。这是您可能想要的一个工作示例:

library(ISLR)
library(boot)
data <- data.frame(X = seq_len(100), Y = rnorm(100)) # Reproducible example

MSE <- sapply(seq_len(7), \(i) {
  model <- glm(Y ~ poly(X,i), data = data)
  cv.glm(data, model, K = 2)$delta[1]
})

The problem arises from your use of attach. According to the help page for attach,

The environment is returned invisibly with a "name" attribute.

You stored that environment in the data object. On the other hand, the help page for cv.glm states the "data" argument must be a "matrix or data frame containing the data." You can check this at run time:

> inherits(data, "data.frame")
[1] FALSE

Because data is not a data frame (even though it can behave remarkably like one!), all bets are off when you pass it to cv.glm.

As remarked by a commenter, delete the attach call: it's superfluous (and has invisible side-effects anyway). Here is a working example of what you likely intended:

library(ISLR)
library(boot)
data <- data.frame(X = seq_len(100), Y = rnorm(100)) # Reproducible example

MSE <- sapply(seq_len(7), \(i) {
  model <- glm(Y ~ poly(X,i), data = data)
  cv.glm(data, model, K = 2)$delta[1]
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文