【问题标题】:R - longer object length is not a multiple of shorter object lengthR - 较长的对象长度不是较短对象长度的倍数
【发布时间】:2018-08-03 20:15:26
【问题描述】:

我正在这样做:

RMSE <- (sum((RFestimated-model1$y)^2)/length(model1$y))^(1/2)

在哪里: mode1 是来自随机森林的回归模型,y 是从训练数据中预测的值 RFestimated 是来自测试数据的预测值

我正在尝试计算 RMSE 有没有使长度相等的技巧?

这些是我的步骤:(代码)

# sample 80% of the data for training -random sample
train_index <- sample(1:nrow(beijingData), 0.8 * nrow(beijingData))
# take the difference as data to test the model
test_index <- setdiff(1:nrow(beijingData), train_index)

#create Train and Test data sets based on the indexes above.
dataTrain <-  beijingData[train_index,]
dataTest <- beijingData[test_index,]

#check the datasets dimensions
dim(dataTrain)
dim(dataTest)

> dim(dataTrain)
[1] 33405    13
> dim(dataTest)
[1] 8352   13

#set seed
set.seed(100)
#create a random forest regression model
model1 <- randomForest(pm2.5 ~ ., data = dataTrain, ntree=500, importance = 
TRUE)
model1

#predict with test data
RFestimated <- predict(model1, dataTest)

[1] 118.7794
> length(RFestimated)
[1] 8352
> length(model1$y)
[1] 33405

qqnorm((RFestimated - model1$y)/sd(RFestimated-model1$y))

qqline((RFestimated-model1$y)/sd(RFestimated-model1$y))

#results of last tow statements above
> qqnorm((RFestimated - model1$y)/sd(RFestimated-model1$y))
Warning messages:
1: In RFestimated - model1$y :
  longer object length is not a multiple of shorter object length
2: In RFestimated - model1$y :
  longer object length is not a multiple of shorter object length
> 
> qqline((RFestimated-model1$y)/sd(RFestimated-model1$y))
Warning messages:
1: In RFestimated - model1$y :
  longer object length is not a multiple of shorter object length
2: In RFestimated - model1$y :
  longer object length is not a multiple of shorter object length

【问题讨论】:

  • 请参阅How to make a great R reproducible example?。如果您有可重复的示例,您可能会更快地得到问题的答案。提供重现您所要求的内容和所需输出所需的最小输入数据。
  • 我有一种预感,model1$y 是原始的 y,并且长度与您的预测值不同。

标签: r


【解决方案1】:

在这里看看这些行:

#predict with test data
RFestimated <- predict(model1, dataTest)

[1] 118.7794
> length(RFestimated)
[1] 8352
> length(model1$y)
[1] 33405

您看到的是它们的长度不同。这应该如何工作?想想你想要做什么:

a <- c(1,2,3)
b <- c(4,5)
a-b
[1] -3 -3 -1
Warning message:
In a - b : longer object length is not a multiple of shorter object length

您需要在训练数据或测试数据上评估 RMSE,但您将它们混合在一起。也就是说,要么这个

RFestimated <- predict(model1, dataTrain)
qqnorm((RFestimated - model1$y)/sd(RFestimated-model1$y))

会起作用,或者这样:

RFestimated <- predict(model1, dataTest)
qqnorm((RFestimated - dataTest$y)/sd(RFestimated-dataTest$y))

第一个选项告诉您在用于拟合的样本中拟合数据的好坏程度,第二个选项告诉您在测试数据上的表现。

【讨论】:

  • 感谢您指出我的错误。我现在看到我没有比较喜欢和喜欢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2020-07-15
  • 2020-09-09
  • 1970-01-01
相关资源
最近更新 更多