在R中,预测产量错误的长度

时间:2015-01-27 06:52:13

标签: r predict

new.y = predict(model, newx = new.x), new.y的长度与new.x的行长度不同

代码在这里:

install.packages('ISLR')
library(ISLR)

fix(Hitters)   # load data
Hitters = na.omit(Hitters)   # remove NA

x = model.matrix(Salary ~ ., Hitters)[ , -1]
y = Hitters$Salary

set.seed(1)
train = sample(1:nrow(x), nrow(x)/2)   # random sampling
test = (-train)

lm.fit = lm(y ~ x, subset=train)  
lm.pred = predict( lm.fit, newx = x[test,])

dim(x[test,])   # output 132*19
length(lm.pred)   # output 131
length(y[test])   # output 132

有人知道为什么长度错了吗?谢谢!

更新:错误newx = x[test, ]未被predict识别 谢谢@Pascal! 为了使它更明显:

install.packages('ISLR')
library(ISLR)

fix(Hitters)   # load data
Hitters = na.omit(Hitters)   # remove NA

x = model.matrix(Salary ~ ., Hitters)[ , -1]
y = Hitters$Salary

set.seed(2)
train = sample(1:nrow(x), 150)   # random sampling (specify size for testing)
test = (1:nrow(x))[-train]


lm.fit = lm(y ~ x, subset=train)
lm.pred = predict( lm.fit, newx = x[test,])
dim(x[test,])   # output 113  19
length(lm.pred)   # output 150 - still using training data


lm.fit = lm(Salary ~ ., data = Hitters, subset = train)
lm.pred = predict( lm.fit, newdata = Hitters[test,])
dim(x[test,])   # output 113  19
length(lm.pred)   # output 113

在第一个和第二个代码中定义test的方法应该相同。测试:

x = c('A','B','C','D','E')
set.seed(2)
n = length(x)
train = sample(1:n, n/2)   # random sampling
test = -train
test   # output -1 -3
x[test]   # output "B" "D" "E"

test = (1:n)[-train]
test   # output 2 4 5
x[test]   # output "B" "D" "E"

3 个答案:

答案 0 :(得分:1)

您可以简化:

library(ISLR)

Hitters <- na.omit(Hitters)   # remove NA

set.seed(1)
train <- sample(1:nrow(Hitters), nrow(Hitters)/2)   # random sampling
test <- (1:nrow(Hitters))[-train]  # your definition of test was incorrect

lm.fit <- lm(Salary ~ ., data = Hitters, subset = train)  
lm.pred <- predict(lm.fit, newdata = Hitters[test,])

dim(Hitters[test,])   # output 132*20
length(lm.pred)   # output 132

答案 1 :(得分:0)

尝试为参数newdata提供data.frame,如下所示:

lm.pred <- predict(lm.fit,
                   newdata=data.frame(x=x[test,],y=0))

另外,我不确定参数subset是否按照您的想法行事。我会在data的调用中提供lm参数,如:

lm.fit = lm(y ~ x, 
            data=data.frame(x=x,y=y)[train,])  

答案 2 :(得分:0)

试试这个:

install.packages('ISLR')
library(ISLR)

fix(Hitters)   # load data
Hitters = na.omit(Hitters)   # remove NA

x = Hitters[,-1] 
y = Hitters$Salary

set.seed(1)
train = sample(1:nrow(x), nrow(x)/2)   # random sampling
test_data <- x[-train,]
y_test <- y[-train]
y_train<-y[train]
train_data <- data.frame(Y= y[train],x[train,]) 

lm.fit = lm(Y ~ ., train_data)  
lm.pred = predict( lm.fit, newx = test_data)

dim(test_data)   # output 161*19
length(lm.pred)   # output 130
length(y_test)   # output 161

我猜lm.pred长度的差异是由于y

中的空值