我正在使用predict()函数来预测blackFriday_test中的Purchase变量。当我将这些变量用作参数的cor()时,出现“不兼容的尺寸”错误消息。
我尝试在blackFriday_test中查看Purchas变量的维数,即107516,但预测值仅为32955。
数据是从https://www.kaggle.com/mehdidag/black-friday下载的。
library(caret)
blackFriday <- read.csv("BlackFriday.csv", stringsAsFactors = T)
nblackFriday <- blackFriday[, 3:12]
set.seed(189)
train <- sample(nrow(nblackFriday), as.integer(0.8 * nrow(nblackFriday)), replace = F)
blackFriday_train <- nblackFriday[train, ]
blackFriday_test <- nblackFriday[-train, ]
nblackFriday$Product_Category_2 <- ifelse(is.na(nblackFriday$Product_Category_2), mean(nblackFriday$Product_Category_2, na.rm = T), nblackFriday$Product_Category_2)
nblackFriday$Product_Category_3 <- ifelse(is.na(nblackFriday$Product_Category_3), mean(nblackFriday$Product_Category_3, na.rm = T), nblackFriday$Product_Category_3)
blackFriday_train$Product_Category_2 <- nblackFriday$Product_Category_2[train]
blackFriday_train$Product_Category_3 <- nblackFriday$Product_Category_3[train]
m <- train(Purchase ~ ., data = blackFriday_train, method = "rpart")
p <- predict(m, blackFriday_test)
cor(p, blackFriday_test$Purchase)
```
#This is where I get the error
I expect the number of predicted values to be the same as the number of rows in blackFriday_test, but they are not.
答案 0 :(得分:0)
您替换了训练数据集中的缺失值,但没有替换测试数据。因此,您对测试的预测低于测试数据集的行数。
您应在整个数据集上应用您的操作(例如替换NA),然后拆分为训练/测试。这样,您的两个数据集将相似,并且预测将更好地工作。
答案 1 :(得分:0)
您在训练集中替换了NA,但在测试集中替换了不是,因此这些情况被省略了。
> head(blackFriday_test)
Gender Age Occupation City_Category Stay_In_Current_City_Years Marital_Status Product_Category_1
3 F 0-17 10 A 2 0 12
6 M 26-35 15 A 3 0 1
15 F 51-55 9 A 1 0 5
16 F 51-55 9 A 1 0 4
21 M 26-35 12 C 4+ 1 5
22 M 26-35 12 C 4+ 1 8
Product_Category_2 Product_Category_3 Purchase
3 NA NA 1422
6 2 NA 15227
15 8 14 5378
16 5 NA 2079
21 14 NA 8584
22 NA NA 9872
就像为预期的训练集所做的那样估算他们。
blackFriday_test$Product_Category_2 <- nblackFriday$Product_Category_2[-train]
blackFriday_test$Product_Category_3 <- nblackFriday$Product_Category_3[-train]
p <- predict(m, blackFriday_test)
> length(p) == nrow(blackFriday_test)
[1] TRUE
> cor(p, blackFriday_test$Purchase)
[1] 0.7405558
尝试使用插入符号本身的分区和预处理功能。对我来说,它们有助于避免这类简单的错误。