我目前正在从事一个基于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),对该数据集进行培训,并在验证集中直接使用它。但是,根据项目说明,这是不允许的。
有什么可能出错的建议吗?
发布于 2019-11-08 09:05:31
只是为了把这个编成一个答案。生成NA的函数是这样做的,因为有些输入已经是NA。
对于大多数偶然的度量标准,如sum、mean、sd等,只需将na.rm = TRUE作为函数参数添加即可。
在你的情况下
mean(x,na.rm= TRUE)https://stackoverflow.com/questions/58762860
复制相似问题