无法在R中计算RMSE

时间:2019-11-08 08:21:11

标签: r machine-learning prediction recommender-systems

我目前正在从事基于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),在该数据集上进行训练并使用它直接放在验证集上。但是,根据项目说明,这是不允许的。

关于可能出什么问题的任何建议?

1 个答案:

答案 0 :(得分:1)

只是将其整理为答案。产生NA的函数之所以会这样做,是因为某些输入已经是NA

在大多数临时指标(例如sum,mean,sd等)的情况下只需将na.rm = TRUE添加为函数参数即可。

以您的情况

mean(x,na.rm= TRUE)