Class: EMAlgorithm::ChiSquare

Inherits:
CheckMethod show all
Defined in:
lib/em_algorithm/convergence/chi_square.rb

Constant Summary collapse

STAT_THRESHOLD =
0.05
CONV_THRESHOLD =
0.01

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_array) ⇒ ChiSquare

Returns a new instance of ChiSquare.



8
9
10
11
# File 'lib/em_algorithm/convergence/chi_square.rb', line 8

def initialize(data_array)
  @data_array = data_array
  @history = []
end

Instance Attribute Details

#historyObject

Returns the value of attribute history.



6
7
8
# File 'lib/em_algorithm/convergence/chi_square.rb', line 6

def history
  @history
end

Instance Method Details

#calculate(model, const) ⇒ Object

calculate chi square



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/em_algorithm/convergence/chi_square.rb', line 14

def calculate(model, const)
  chi_square = 0.0
  @data_array.each do |x|
    value = x[x.size-1]
    pdf = model.pdf(x[0..(x.size-2)])
    next if value <= 1.0
    estimated = const * pdf
    chi_square += (value - estimated)**2 / estimated
  end
  @history << chi_square
  chi_square
end

#converged?Boolean

Returns:

  • (Boolean)


31
32
33
34
# File 'lib/em_algorithm/convergence/chi_square.rb', line 31

def converged?
  return false if @history.length == 1
  (@history[-1] < STAT_THRESHOLD) || ((@history[-1] - @history[-2]).abs < CONV_THRESHOLD)
end

#debug_outputObject



36
37
38
# File 'lib/em_algorithm/convergence/chi_square.rb', line 36

def debug_output
  $stderr.puts "ChiSquare: #{value}"
end

#valueObject



27
28
29
# File 'lib/em_algorithm/convergence/chi_square.rb', line 27

def value
  @history.last
end