Method: Evoc::Evaluate.t_ap

Defined in:
lib/evoc/evaluate.rb

.t_ap(rec:, exp: nil) ⇒ Object

r_p : relevant items in previous groups i_p : index previous group r_g : relevant items in group n_g : items in group i : index of current item



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
# File 'lib/evoc/evaluate.rb', line 205

def self.t_ap(rec:,exp: nil)
  # AP is 0 for the empty list
  if rec.is_a?(Array) && rec.empty? # array and empty
    return nil
  end
  self.validateInput(rec)

  ap = 0
  r_p = 0
  i_p = 0
  rec.each do |cluster|
    r_g = cluster.inject(&:+).to_r
    n_g = cluster.size.to_r
    cluster.each_with_index do |_,i|
      i = i_p + i + 1
      chance_relevant = r_g/n_g
      avg_previous_rel = if (n_g == 1)
                           (r_p + 1) * (1/i)
                         else
                           (r_p + (i - i_p - 1)*((r_g-1)/(n_g-1)) + 1) * (1/i)
                         end

      item_ap_contribution = chance_relevant * avg_previous_rel

      ap = ap + item_ap_contribution
    end
    r_p = r_p + r_g
    i_p = i_p + n_g
  end
  # if the number of relevant documents is not supplied
  # assume that the recommendation contains all relevant documents
  if exp.nil?
    exp = r_p
  else
    if r_p > exp
      raise ArgumentError, "Found more relevant items than the provided number of relevant items"
    end
  end
  return (r_p == 0 ? 0 : (ap/exp).to_f)
end