R的predict函数可以带newdata参数,其文档如下:
newdata一个可选的数据框,用于查找要预测的变量.如果省略,则使用拟合值.
但我发现这并不完全正确,这取决于模型的拟合程度.例如,以下代码按预期工作:
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"))
Run Code Online (Sandbox Code Playgroud)
但如果模型适合这样:
m2 <- lm(dataTrain$y ~ dataTrain$x)
head(predict(m2,type="response"))
head(predict(m2,newdata=dataTest,type="response"))
Run Code Online (Sandbox Code Playgroud)
最后两行将产生完全相同的结果.该predict函数以忽略newdata参数的方式工作,即它根本无法真正计算对新数据的预测.
罪魁祸首,当然是lm(y ~ x, data=dataTrain)对lm(dataTrain$y ~ dataTrain$x).但我没有找到任何提到这两者之间差异的文件.这是一个已知的问题吗?
我正在使用R 2.15.2.
Rei*_*son 12
请参阅?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.
Run Code Online (Sandbox Code Playgroud)
虽然它没有以"同名"等方式陈述行为,但就公式而言,你传递给它的术语是形式的foo$var,并且没有这样的变量,其名称就像newdata在R将遍历以查找它们的搜索路径.
在你的第二种情况下,你完全滥用模型公式表示法; 这个想法是简洁而象征性地描述模型.简洁和重复数据对象与恶心不相容.
您注意到的行为与记录的行为完全一致.简单地说,你配有条款的模型data$x,并data$y随后试图预测方面x和y.就R来说,这些是不同的名称,因此是不同的东西,并且没有匹配它们是正确的.
| 归档时间: |
|
| 查看次数: |
16470 次 |
| 最近记录: |