余弦相似度:函数不能计算矩阵

Cosine Similarity: Funtion Can't Calculate The Matrix

所以,我最近在 Rstudio 中使用协同过滤构建了一个音乐推荐系统。我对余弦相似度函数有一些问题,系统在我要计算的矩阵上说 "subscript out of bond"。

我使用从该网站获得参考的余弦相似度:https://bgstieber.github.io/post/recommending-songs-using-cosine-similarity-in-r/

我已尝试修复脚本,但显然输出仍无法正常工作。

##cosinesim-crossprod
cosine_sim <- function(a,b) {crossprod(a,b)/sqrt(crossprod(a)*crossprod(b))}

##User data
play_data <- "https://static.turi.com/datasets/millionsong/10000.txt" %>%
  read_tsv(col_names = c('user', 'song_id', 'plays'))

##Song data
song_data <- read_csv("D:/3rd Term/DataAnalysis/dataSet/song_data.csv") %>%
  distinct(song_id, title, artist_name)

##Grouped
all_data <- play_data %>%
  group_by(user, song_id) %>%
  summarise(plays = sum(plays, na.rm = TRUE)) %>%
  inner_join(song_data)

top_1k_songs <- all_data %>%
  group_by(song_id, title, artist_name) %>%
  summarise(sum_plays = sum(plays)) %>%
  ungroup() %>%
  top_n(1000, sum_plays) %>% 
  distinct(song_id)

all_data_top_1k <- all_data %>%
  inner_join(top_1k_songs)

top_1k_wide <- all_data_top_1k %>%
  ungroup() %>%
  distinct(user, song_id, plays) %>%
  spread(song_id, plays, fill = 0)

ratings <- as.matrix(top_1k_wide[,-1])

##Function
calc_cos_sim <- function(song_code = top_1k_songs, 
                         rating_mat = ratings,
                         songs = song_data,
                         return_n = 5) {
  song_col_index <- which(colnames(ratings)== song_code) %>%
  cos_sims <- apply(rating_mat, 2,FUN = function(y) 
                      cosine_sim(rating_mat[,song_col_index], y))
##output
  data_frame(song_id = names(cos_sims), cos_sim = cos_sims) %>%
    filter(song_id != song_code) %>% # remove self reference
    inner_join(songs) %>%
    arrange(desc(cos_sim)) %>%
    top_n(return_n, cos_sim) %>%
    select(song_id, title, artist_name, cos_sim)
}

我希望当我使用这个脚本时:

shots <- 'SOJYBJZ12AB01801D0'
knitr::kable(calc_cos_sim(shots))

输出将是 5 首歌曲的数据框。

这一行末尾的竖线看起来像是错字:

song_col_index <- which(colnames(ratings)== song_code) %>%

替换为:

song_col_index <- which(colnames(ratings)== song_code)