Class: Cmfrec::Recommender

Inherits:
Object
  • Object
show all
Defined in:
lib/cmfrec/recommender.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(factors: 8, epochs: 10, verbose: true, user_bias: true, item_bias: true, add_implicit_features: false) ⇒ Recommender

Returns a new instance of Recommender.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/cmfrec/recommender.rb', line 5

def initialize(factors: 8, epochs: 10, verbose: true, user_bias: true, item_bias: true, add_implicit_features: false)
  set_params(
    k: factors,
    niter: epochs,
    verbose: verbose,
    user_bias: user_bias,
    item_bias: item_bias,
    add_implicit_features: add_implicit_features
  )

  @fit = false
  @user_map = {}
  @item_map = {}
  @user_info_map = {}
  @item_info_map = {}
end

Instance Attribute Details

#global_meanObject (readonly)

Returns the value of attribute global_mean.



3
4
5
# File 'lib/cmfrec/recommender.rb', line 3

def global_mean
  @global_mean
end

Class Method Details

.load_json(json) ⇒ Object



304
305
306
307
308
309
310
311
312
# File 'lib/cmfrec/recommender.rb', line 304

def self.load_json(json)
  require "json"

  obj = JSON.parse(json)

  recommender = new
  recommender.send(:json_load, obj)
  recommender
end

Instance Method Details

#fit(train_set, user_info: nil, item_info: nil) ⇒ Object



22
23
24
25
# File 'lib/cmfrec/recommender.rb', line 22

def fit(train_set, user_info: nil, item_info: nil)
  reset
  partial_fit(train_set, user_info: , item_info: item_info)
end

#item_bias(item_id = nil) ⇒ Object



237
238
239
# File 'lib/cmfrec/recommender.rb', line 237

def item_bias(item_id = nil)
  read_bias(@bias_b, item_id, @item_map) if @bias_b
end

#item_factors(item_id = nil) ⇒ Object



229
230
231
# File 'lib/cmfrec/recommender.rb', line 229

def item_factors(item_id = nil)
  read_factors(@b, [@n, @n_i].max, @k_item + @k + @k_main, item_id, @item_map)
end

#item_idsObject



221
222
223
# File 'lib/cmfrec/recommender.rb', line 221

def item_ids
  @item_map.keys
end

#new_user_recs(data, count: 5, user_info: nil, item_ids: nil) ⇒ Object



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
# File 'lib/cmfrec/recommender.rb', line 81

def new_user_recs(data, count: 5, user_info: nil, item_ids: nil)
  check_fit

  data = to_dataset(data)
   = to_dataset() if 

  # remove unknown items
  data, unknown_data = data.partition { |d| @item_map[d[:item_id]] }

  if unknown_data.any?
    # TODO warn for unknown items?
    # warn "[cmfrec] Unknown items: #{unknown_data.map { |d| d[:item_id] }.join(", ")}"
  end

  rated_ids = data.map { |d| @item_map[d[:item_id]] }

  nnz = data.size

  u_vec_sp = []
  u_vec_x_col = []
  if 
    .each do |k, v|
      next if k == :user_id

      uc = @user_info_map[k]
      raise "Bad key: #{k}" unless uc

      u_vec_x_col << uc
      u_vec_sp << v
    end
  end
  p_ = @user_info_map.size
  nnz_u_vec = u_vec_sp.size
  u_vec_x_col = int_ptr(u_vec_x_col)
  u_vec_sp = real_ptr(u_vec_sp)

  u_vec = nil
  u_bin_vec = nil
  pbin = 0

  weight = nil
  lam_unique = nil
  l1_lam_unique = nil
  n_max = @n

  if data.any?
    if @implicit
      ratings = data.map { |d| d[:value] || 1 }
    else
      ratings = data.map { |d| d[:rating] }
      check_ratings(ratings)
    end
    xa = real_ptr(ratings)
    x_col = int_ptr(rated_ids)
  else
    xa = nil
    x_col = nil
  end
  xa_dense = nil

  rated = rated_ids.uniq

  prep = prepare_top_n(count: count, rated: rated, item_ids: item_ids)
  return [] if prep.empty?
  include_ix, n_include, exclude_ix, n_exclude, outp_ix, outp_score, count = prep

  if @implicit
    args = [
      @n,
      u_vec, p_,
      u_vec_sp, u_vec_x_col, nnz_u_vec,
      @na_as_zero_user,
      @nonneg,
      @u_colmeans,
      @b, @c,
      xa, x_col, nnz,
      @k, @k_user, @k_item, @k_main,
      @lambda_, @l1_lambda, @alpha, @w_main, @w_user,
      @w_main_multiplier,
      @apply_log_transf,
      nil, #BeTBe,
      nil, #BtB,
      nil, #BeTBeChol,
      nil, #CtUbias,
      include_ix, n_include,
      exclude_ix, n_exclude,
      outp_ix, outp_score,
      count, @nthreads
    ]
    check_status FFI.topN_new_collective_implicit(*fiddle_args(args))
  else
    cb = nil
    scaling_bias_a = 0

    args = [
      @user_bias,
      u_vec, p_,
      u_vec_sp, u_vec_x_col, nnz_u_vec,
      u_bin_vec, pbin,
      @na_as_zero_user, @na_as_zero,
      @nonneg,
      @c, cb,
      @global_mean, @bias_b,
      @u_colmeans,
      xa, x_col, nnz,
      xa_dense, @n,
      weight,
      @b,
      @bi, @add_implicit_features,
      @k, @k_user, @k_item, @k_main,
      @lambda_, lam_unique,
      @l1_lambda, l1_lam_unique,
      @scale_lam, @scale_lam_sideinfo,
      @scale_bias_const, scaling_bias_a,
      @w_main, @w_user, @w_implicit,
      n_max, @include_all_x,
      nil, #BtB,
      nil, #TransBtBinvBt,
      nil, #BtXbias,
      nil, #BeTBeChol,
      nil, #BiTBi,
      nil, #CtCw,
      nil, #TransCtCinvCt,
      nil, #CtUbias,
      nil, #B_plus_bias,
      include_ix, n_include,
      exclude_ix, n_exclude,
      outp_ix, outp_score,
      count, @nthreads
    ]
    check_status FFI.topN_new_collective_explicit(*fiddle_args(args))
  end

  top_n_output(outp_ix, outp_score)
end

#predict(data) ⇒ Object



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
# File 'lib/cmfrec/recommender.rb', line 27

def predict(data)
  check_fit

  data = to_dataset(data)

  u = data.map { |v| @user_map[v[:user_id]] || @user_map.size }
  i = data.map { |v| @item_map[v[:item_id]] || @item_map.size }

  row = int_ptr(u)
  col = int_ptr(i)
  n_predict = data.size
  predicted = Fiddle::Pointer.malloc(n_predict * Fiddle::SIZEOF_DOUBLE)

  if @implicit
    check_status FFI.predict_X_old_collective_implicit(
      row, col, predicted, n_predict,
      @a, @b,
      @k, @k_user, @k_item, @k_main,
      @m, @n,
      @nthreads
    )
  else
    check_status FFI.predict_X_old_collective_explicit(
      row, col, predicted, n_predict,
      @a, @bias_a,
      @b, @bias_b,
      @global_mean,
      @k, @k_user, @k_item, @k_main,
      @m, @n,
      @nthreads
    )
  end

  predictions = real_array(predicted)
  predictions.map! { |v| v.nan? ? @global_mean : v } if @implicit
  predictions
end

#similar_items(item_id, count: 5) ⇒ Object Also known as: item_recs



241
242
243
244
# File 'lib/cmfrec/recommender.rb', line 241

def similar_items(item_id, count: 5)
  check_fit
  similar(item_id, @item_map, item_factors, count, item_index)
end

#similar_users(user_id, count: 5) ⇒ Object



247
248
249
250
# File 'lib/cmfrec/recommender.rb', line 247

def similar_users(user_id, count: 5)
  check_fit
  similar(user_id, @user_map, user_factors, count, user_index)
end

#to_jsonObject



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/cmfrec/recommender.rb', line 252

def to_json
  require "base64"
  require "json"

  obj = {
    implicit: @implicit
  }

  # options
  obj[:factors] = @k
  obj[:epochs] = @niter
  obj[:verbose] = @verbose

  # factors
  obj[:user_ids] = @user_map.keys
  obj[:item_ids] = @item_map.keys
  obj[:rated] = @user_map.map { |_, u| (@rated[u] || {}).keys }
  obj[:user_factors] = json_dump_ptr(@a)
  obj[:item_factors] = json_dump_ptr(@b)

  # bias
  obj[:user_bias] = json_dump_ptr(@bias_a)
  obj[:item_bias] = json_dump_ptr(@bias_b)

  # mean
  obj[:global_mean] = @global_mean

  unless (@user_info_map.keys + @item_info_map.keys).all? { |v| v.is_a?(Symbol) }
    raise "Side info keys must be symbols to save"
  end

  # side info
  obj[:user_info_ids] = @user_info_map.keys
  obj[:item_info_ids] = @item_info_map.keys
  obj[:user_info_factors] = json_dump_ptr(@c)
  obj[:item_info_factors] = json_dump_ptr(@d)

  # implicit features
  obj[:add_implicit_features] = @add_implicit_features
  obj[:user_factors_implicit] = json_dump_ptr(@ai)
  obj[:item_factors_implicit] = json_dump_ptr(@bi)

  unless @implicit
    obj[:min_rating] = @min_rating
    obj[:max_rating] = @max_rating
  end

  obj[:user_means] = json_dump_ptr(@u_colmeans)

  JSON.generate(obj)
end

#user_bias(user_id = nil) ⇒ Object



233
234
235
# File 'lib/cmfrec/recommender.rb', line 233

def user_bias(user_id = nil)
  read_bias(@bias_a, user_id, @user_map) if @bias_a
end

#user_factors(user_id = nil) ⇒ Object



225
226
227
# File 'lib/cmfrec/recommender.rb', line 225

def user_factors(user_id = nil)
  read_factors(@a, [@m, @m_u].max, @k_user + @k + @k_main, user_id, @user_map)
end

#user_idsObject



217
218
219
# File 'lib/cmfrec/recommender.rb', line 217

def user_ids
  @user_map.keys
end

#user_recs(user_id, count: 5, item_ids: nil) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/cmfrec/recommender.rb', line 65

def user_recs(user_id, count: 5, item_ids: nil)
  check_fit
  user = @user_map[user_id]

  if user
    a_vec = @a[user * @k * Fiddle::SIZEOF_DOUBLE, @k * Fiddle::SIZEOF_DOUBLE]
    a_bias = @bias_a ? @bias_a[user * Fiddle::SIZEOF_DOUBLE, Fiddle::SIZEOF_DOUBLE].unpack1("d") : 0
    # @rated[user] will be nil for recommenders saved before 0.1.5
    top_n(a_vec: a_vec, a_bias: a_bias, count: count, rated: (@rated[user] || {}).keys, item_ids: item_ids, row_index: user)
  else
    # no items if user is unknown
    # TODO maybe most popular items
    []
  end
end