【问题标题】:Trouble calculating RMSE in R在 R 中计算 RMSE 时遇到问题
【发布时间】:2020-03-04 20:49:54
【问题描述】:

我目前正在从事一个基于 MovieLens、Netflix 数据的数据科学项目。

我已经像这样拆分了测试集和训练集:

# Test set will be 10% of current MovieLens data
set.seed(1, sample.kind="Rounding")
# if using R 3.5 or earlier, use `set.seed(1)` instead
test_index2 <- createDataPartition(y = edx$rating, times = 1, p = 0.1, list = FALSE)
train_set <- edx[-test_index2,]
test_set <- edx[test_index2,]

我必须根据这个函数计算预测评级的 RMSE:

#Define the function that calculates RMSE
RMSE <- function(true_ratings, predicted_ratings){
sqrt(mean((true_ratings - predicted_ratings)^2))
}

首先,我使用最简单的模型进行此操作,如下所示:

#Get mu_hat with the simplest model
mu_hat <- mean(train_set$rating)
mu_hat
[1] 3.512457

#Predict the known ratings with mu_hat
naive_rmse <- RMSE(test_set$rating, mu_hat)
naive_rmse
[1] 1.060056

#Create the results table
rmse_results <- tibble(method = "Simple average model", RMSE = naive_rmse)

接下来,我需要使用一个对电影效果进行惩罚的模型:

#Penalize movie effects and adjust the mean
b_i <- train_set %>% group_by(movieId) %>%
summarize(b_i = sum(rating - mu_hat)/(n() + 1))

#Save and plot the movie averages with the movie effect model
movie_effect_avgs <- train_set %>% group_by(movieId) %>% summarize(b_i = mean(rating - mu_hat))
movie_effect_avgs %>% qplot(b_i, geom = "histogram", bins = 10, data = ., color = I("azure3"), xlab = "Number of movies with b_i", ylab = "Number of movies")

#Save the new predicted ratings
predicted_ratings <- mu_hat + test_set %>% left_join(movie_effect_avgs, by='movieId') %>%
pull(b_i)

预测评分的第一行如下所示:

predicted_ratings
   [1] 3.130763 4.221028 3.742687 3.429529 3.999581 4.278903 3.167818 3.332393

我的问题出现在这里:

#Calculate the RMSE for the movie effect model
movie_effect_rmse <- RMSE(predicted_ratings, test_set$rating)
movie_effect_rmse
[1] NA

它只是说“NA”,而不是给我第二个模型的 RMSE 值,但我无法理解我的代码有什么问题或 RMSE 函数为什么不起作用。我怀疑它与测试/训练集的结构有关。如果我按照上述完全相同的步骤操作,代码就可以工作,但相反,我从 之前 获取数据集,我已经进一步拆分为测试和训练(称为 edx),在该数据集上进行训练并使用它直接在验证集上。但是,根据项目的说明,这是不允许的。

有什么可能出错的建议吗?

【问题讨论】:

  • 你的 predict_ratings 中有 NA 吗?
  • 我没有检查过,但我只是尝试过。显然,有 17 个 NA。会不会是这个问题?
  • @SarahTomori 在这种情况下在您的原始函数中使用 mean(x,na.rm = TRUE)。
  • 请注意,尽管这“解决”了 coding 问题,但它很可能只是掩盖了一个潜在的真正 modelling 问题,这会导致 RMSE 值首先要成为NA,这是不应该发生的事情cc @Fnguyen
  • 几个月前当我偶然发现this thread 时,我简直不敢相信自己的眼睛,其中有一大堆“答案”(包括接受的答案,在编辑之前) 建议操纵模型输出以使代码正常运行,而不是指出明显的 建模 错误(尝试使用回归模型进行分类)。

标签: r machine-learning prediction recommender-systems


【解决方案1】:

只是将其编码为答案。产生NA 的函数这样做是因为一些输入已经是NA。

对于大多数随意的指标,如 sum、mean、sd 等。只需添加 na.rm = TRUE 作为函数参数即可。

你的情况

mean(x,na.rm= TRUE)

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2021-03-02
    相关资源
    最近更新 更多