/
RECOM_UBCF.R
275 lines (230 loc) · 7.04 KB
/
RECOM_UBCF.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# User-Based Collaborative Filtering
## simple k-nearest
## returns a list with up to k neighbors for each user
# FIXME: check if we have enough neighbors (warning?)
.knn <- function(sim, k)
lapply(
1:nrow(sim),
FUN = function(i)
head(order(
sim[i,], decreasing = TRUE, na.last = NA
), k)
)
.BIN_UBCF_param <- list(
method = "jaccard",
nn = 25,
weighted = TRUE,
sample = FALSE,
min_matching_items = 0,
min_predictive_items = 0
)
BIN_UBCF <- function(data, parameter = NULL) {
p <- getParameters(.BIN_UBCF_param, parameter)
if (p$sample)
data <- sample(data, p$sample)
model <- c(
list(description = "UBCF-Binary Data: contains full or sample of data set",
data = data),
p
)
predict <- function(model,
newdata,
n = 10,
data = NULL,
type = c("topNList", "ratings", "ratingMatrix"),
...) {
type <- match.arg(type)
newdata_id <- NULL
## newdata are userid
if (is.numeric(newdata)) {
if (model$sample)
stop("User id in newdata does not work when sampling is used!")
newdata_id <- newdata
newdata <- model$data[newdata,]
} else if (ncol(newdata) != ncol(model$data))
stop("number of items in newdata does not match model.")
## prediction
## FIXME: add Weiss dissimilarity
sim <- similarity(
newdata,
model$data,
method = model$method,
min_matching = model$min_matching_items,
min_predictive = model$min_predictive_items
)
## FIXME: remove self matches!
if (!is.null(newdata_id))
sim[cbind(seq(length(newdata_id)), newdata_id)] <- NA
neighbors <- .knn(sim, model$nn)
if (model$weighted) {
## similarity of the neighbors
s_uk <- sapply(
1:nrow(sim),
FUN = function(i)
sim[i, neighbors[[i]]]
)
if (!is.matrix(s_uk))
s_uk <- as.matrix(t(s_uk))
## calculate the weighted sum
ratings <- t(sapply(
1:nrow(newdata),
FUN = function(i) {
## neighbors ratings of active user i
r_neighbors <- as(model$data[neighbors[[i]]], "dgCMatrix")
## normalize by the sum by the number of neighbors
drop(as(crossprod(r_neighbors, s_uk[, i]), "matrix")) /
colSums(!dropNAis.na(r_neighbors))
}
))
} else{
ratings <- t(sapply(
1:nrow(newdata),
FUN = function(i) {
colCounts(model$data[neighbors[[i]]])
}
))
}
rownames(ratings) <- rownames(newdata)
ratings <- new("realRatingMatrix", data = dropNA(ratings))
## prediction done
returnRatings(ratings, newdata, type, n)
}
## construct recommender object
new(
"Recommender",
method = "UBCF",
dataType = class(data),
ntrain = nrow(data),
model = model,
predict = predict
)
}
.REAL_UBCF_param <- list(
method = "cosine",
nn = 25,
sample = FALSE,
weighted = TRUE,
normalize = "center",
min_matching_items = 0,
min_predictive_items = 0
)
REAL_UBCF <- function(data, parameter = NULL) {
p <- getParameters(.REAL_UBCF_param, parameter)
if (p$sample)
data <- sample(data, p$sample)
## normalize data
if (!is.null(p$normalize))
data <- normalize(data, method = p$normalize)
model <-
c(list(description = "UBCF-Real data: contains full or sample of data set",
data = data),
p)
predict <- function(model,
newdata,
n = 10,
data = NULL,
type = c("topNList", "ratings", "ratingMatrix"),
...) {
type <- match.arg(type)
newdata_id <- NULL
## newdata are userid
if (is.numeric(newdata)) {
if (model$sample)
stop("User id in newdata does not work when sampling is used!")
newdata_id <- newdata
newdata <- model$data[newdata,]
} else {
if (ncol(newdata) != ncol(model$data))
stop("number of items in newdata does not match model.")
if (!is.null(model$normalize))
newdata <- normalize(newdata, method = model$normalize)
}
## predict ratings
sim <- similarity(
newdata,
model$data,
method = model$method,
min_matching = model$min_matching_items,
min_predictive = model$min_predictive_items
)
## FIXME: remove self matches!
if (!is.null(newdata_id))
sim[cbind(seq(length(newdata_id)), newdata_id)] <- NA
neighbors <- .knn(sim, model$nn)
# Note: we may get less than k neighbors!
## r_ui = r_u_bar + [sum_k s_uk * r_ai - r_a_bar] / sum_k s_uk
## k is the neighborhood
## r_ai - r_a_bar_ is normalize(r_ai) = newdata
if (model$weighted) {
# average ratings weighted by similarity. This is a list so we can have a
# different number of nn for each user.
s_uk <- lapply(
seq(nrow(sim)),
FUN = function(i)
sim[i, neighbors[[i]]]
)
ratings <- t(sapply(
seq(nrow(newdata)),
FUN = function(i) {
## Seems like we do not need to check for no nearest neighbor
#if (length(neighbors[[i]]) < 1)
# return(rep(NA_real_, times = ncol(model$data)))
## neighbors ratings of active user i
r_neighbors <- as(model$data[neighbors[[i]]], "dgCMatrix")
## normalize by the sum of weights only if a rating is available
drop(as(crossprod(r_neighbors, s_uk[[i]]), "matrix")) /
drop(as(crossprod(
!dropNAis.na(r_neighbors), s_uk[[i]]
), "matrix"))
}
))
ratings[!is.finite(ratings)] <- NA ### make NaN into NA
} else{
### unweighted average
ratings <- t(sapply(
seq(nrow(newdata)),
FUN = function(i) {
## return nothing if we no nearest neighbor
if (length(neighbors[[i]]) < 1)
return(rep(NA_real_, times = ncol(model$data)))
## neighbors ratings of active user i
r_neighbors <- as(model$data[neighbors[[i]]], "dgCMatrix")
## normalize by the sum of weights only if a rating is available
colSums(r_neighbors) / colSums(!dropNAis.na(r_neighbors))
}
))
ratings[!is.finite(ratings)] <- NA_real_ ### make NaN into NA
}
### Note: If no user in the neighborhood has a rating for the item then it is NA!
rownames(ratings) <- rownames(newdata)
ratings <- new("realRatingMatrix",
data = dropNA(ratings),
normalize = getNormalize(newdata))
ratings <- denormalize(ratings)
returnRatings(ratings, newdata, type, n)
}
## construct recommender object
new(
"Recommender",
method = "UBCF",
dataType = class(data),
ntrain = nrow(data),
model = model,
predict = predict
)
}
## register recommender
recommenderRegistry$set_entry(
method = "UBCF",
dataType = "binaryRatingMatrix",
fun = BIN_UBCF,
description = "Recommender based on user-based collaborative filtering.",
parameters = .BIN_UBCF_param
)
recommenderRegistry$set_entry(
method = "UBCF",
dataType = "realRatingMatrix",
fun = REAL_UBCF,
description = "Recommender based on user-based collaborative filtering.",
parameters = .REAL_UBCF_param
)