gpt4 book ai didi

r - 在 R 中计算 RMSE 时遇到问题

转载 作者:行者123 更新时间:2023-11-30 09:40:53 25 4
gpt4 key购买 nike

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

对可能出现的问题有什么建议吗?

最佳答案

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

对于大多数随意的指标,如总和、平均值、标准差等。只需添加 na.rm = TRUE 作为函数参数即可。

就你的情况

mean(x,na.rm= TRUE)

关于r - 在 R 中计算 RMSE 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58762860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com