Module: Azami

Defined in:
lib/azami.rb

Overview

Azami

Class Method Summary collapse

Class Method Details

.em(data) ⇒ Object



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
# File 'lib/azami.rb', line 3

def self.em(data)
  inputs = data[:inputs]
  normal_params = data[:normal_params]
  iteration_count = data[:iteration_count]

  iteration_count.times do
    likelihood_weights =
      inputs.map do |input|
        likelihoods = normal_params.map do |normal_param|
          mean = normal_param[:mean]
          stdev = normal_param[:stdev]
          (0.398942 * (2.71828**(-(0.5 * (input - mean)**2) / stdev**2))) / stdev
        end
        total_likelihood = likelihoods.sum
        likelihoods.map do |lk|
          lk / total_likelihood
        end
      end.transpose

    normal_params.each_with_index do |normal_param, normal_index|
      weights = likelihood_weights[normal_index]
      weights_sum = weights.sum
      normal_param[:mean] = mean = weights.map.with_index do |weight, input_i|
                                      (weight * inputs[input_i])
                                    end .sum / weights_sum
      normal_param[:stdev] = Math.sqrt((weights.map.with_index do |weight, input_i|
                                           (((inputs[input_i] - mean)**2) * weight)
                                         end).sum / weights_sum)
    end
  end
  normal_params
end