-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimilarity_measures.R
48 lines (38 loc) · 1.24 KB
/
similarity_measures.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# ============================================================
# Similarity measures for sparse matrices.
# ============================================================
#' Calculates correlations between columns of two sparse matrices.
#'
#' @param X (dgCMatrix)
#' @param Y (dgCMatrix)
#' @returns Matrix of correlations.
#' @note Requeres {recommenderlab} package for normalization.
cal_cor <- function(X, Y){
availX <- X!=0
availY <- Y!=0
# normalization
X<- as(normalize(as(X, "realRatingMatrix"), method = "center", row = FALSE), "dgCMatrix")
Y<- as(normalize(as(Y, "realRatingMatrix"), method = "center", row = FALSE), "dgCMatrix")
R <- crossprod(X,Y)
N <- crossprod(X^2, availY)
M <- crossprod(availX, Y^2)
cor <- R
cor@x <- cor@x/((N@x^0.5) * (M@x^0.5))
cor
}
#' Calculates cosine between columns of two sparse matrices.
#'
#' @param X (dgCMatrix)
#' @param Y (dgCMatrix)
#' @returns Matrix of cosine measures.
cal_cos <- function(X, Y){
ones <- rep(1,nrow(X))
means <- drop(crossprod(X^2, ones)) ^ 0.5
diagonal <- Diagonal( x = means^-1 )
X <- X %*% diagonal
ones <- rep(1,nrow(Y))
means <- drop(crossprod(Y^2, ones)) ^ 0.5
diagonal <- Diagonal( x = means^-1 )
Y <- Y %*% diagonal
crossprod(X, Y)
}