余弦相似度:函数无法计算矩阵

时间:2019-09-07 09:50:24

标签: r machine-learning recommender-systems

因此,我最近在Rstudio中使用“协作过滤”构建了音乐推荐系统。余弦相似度函数存在一些问题,系统会在要计算的矩阵上说“下标不存在键”。

我使用余弦相似度,该余弦相似度来自以下网站: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首歌曲的数据帧。

1 个答案:

答案 0 :(得分:0)

此行末尾的管道看起来像错字:

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

替换为:

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