Module: NaiveBayesRb::Stats

Extended by:
Stats
Included in:
Stats
Defined in:
lib/naive_bayes_rb/stats.rb

Instance Method Summary collapse

Instance Method Details

#accuracy(predictions, target) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/naive_bayes_rb/stats.rb', line 27

def accuracy(predictions, target)
  predictions.zip(target)
             .map {|x| x[0] == x[1]}
             .count {|x| x}
             .send(:*, 100.0)
             .send(:/, predictions.length)
end

#class_probability(value, summaries) ⇒ Object



17
18
19
20
21
# File 'lib/naive_bayes_rb/stats.rb', line 17

def class_probability(value, summaries)
  summaries.inject({}) { |h, (k, v)| 
    h[k] = v.zip(Array(value)).inject(1) { |p, ms|
      p * probability(ms[1], ms[0][0], ms[0][1])}; h}
end

#mean_stdev(data) ⇒ Object



5
6
7
8
9
10
# File 'lib/naive_bayes_rb/stats.rb', line 5

def mean_stdev(data)
  dimension = data[0].length-1
  means = (0..dimension).map {|i| mean(data.map {|x| x[i]})}
  stdevs = (0..dimension).map {|i| stdev(data.map {|x| x[i]})}
  means.zip(stdevs)
end

#prediction(value, summaries) ⇒ Object



23
24
25
# File 'lib/naive_bayes_rb/stats.rb', line 23

def prediction(value, summaries)
  class_probability(value, summaries).sort_by {|_, v| -v}.first.first
end

#probability(value, mean, stdev) ⇒ Object



12
13
14
15
# File 'lib/naive_bayes_rb/stats.rb', line 12

def probability(value, mean, stdev)
  exponent = Math.exp(-((value-mean)**2)/( 2 * stdev**2 ))
  (1 / (Math.sqrt(2*Math::PI) * stdev) ) * exponent
end