gpt4 book ai didi

r - 向R预测函数馈送新数据

转载 作者:行者123 更新时间:2023-12-04 10:40:28 24 4
gpt4 key购买 nike

R的predict函数可以采用newdata参数,其文档显示为:

newdata An optional data frame in which to look for variables with which to predict. If omitted, the fitted values are used.



但是我发现,取决于模型的拟合程度,这并非完全正确。例如,以下代码可以正常工作:
x <- rnorm(200, sd=10)
y <- x + rnorm(200, sd=1)
data <- data.frame(x, y)
train = sample(1:length(x), size=length(x)/2, replace=F)
dataTrain <- data[train,]
dataTest <- data[-train,]
m <- lm(y ~ x, data=dataTrain)
head(predict(m,type="response"))
head(predict(m,newdata=dataTest,type="response"))

但是,如果模型适合这样:
m2 <- lm(dataTrain$y ~ dataTrain$x)
head(predict(m2,type="response"))
head(predict(m2,newdata=dataTest,type="response"))

最后两行将产生完全相同的结果。 predict函数的工作方式忽略了 newdata参数,即,它根本无法真正计算对新数据的预测。

罪魁祸首当然是 lm(y ~ x, data=dataTrain)lm(dataTrain$y ~ dataTrain$x)。但是我没有找到任何文件提到这两者之间的区别。这是一个已知问题吗?

我正在使用R 2.15.2。

最佳答案

请参阅?predict.lm和“注释”部分,在下面引用:

Note:

Variables are first looked for in ‘newdata’ and then searched for
in the usual way (which will include the environment of the
formula used in the fit). A warning will be given if the
variables found are not of the same length as those in ‘newdata’
if it was supplied.

尽管它没有以“相同名称”等形式说明行为,但就公式而言,您传递给它的术语的格式为 foo$var,并且没有这样的变量,其名称类似于 newdata或沿着搜索路径,R将遍历它们以寻找它们。

在第二种情况下,您完全误用了模型公式符号;这个想法是简洁和象征性地描述模型。简洁和重复数据对象的广告素材不兼容。

您记录的行为 与所记录的行为完全一致。简而言之,您用 data$xdata$y术语对模型进行拟合,然后尝试预测 xy术语。就R而言,这些是不同的名称,因此是不同的事物,并且不匹配它们是正确的。

关于r - 向R预测函数馈送新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com