Class: Newral::Bayes

Inherits:
Object
  • Object
show all
Defined in:
lib/newral/bayes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(theorem) ⇒ Bayes

Returns a new instance of Bayes.



5
6
7
8
# File 'lib/newral/bayes.rb', line 5

def initialize( theorem )
  @theorem = theorem
  @probabilities = {}
end

Instance Attribute Details

#probabilitiesObject (readonly)

Returns the value of attribute probabilities.



4
5
6
# File 'lib/newral/bayes.rb', line 4

def probabilities
  @probabilities
end

#theoremObject (readonly)

Returns the value of attribute theorem.



4
5
6
# File 'lib/newral/bayes.rb', line 4

def theorem
  @theorem
end

Instance Method Details

#add_probability(key, probability, apriori: nil) ⇒ Object



10
11
12
13
# File 'lib/newral/bayes.rb', line 10

def add_probability(key,probability,apriori: nil)
  probability = Probability.new(key,probability,apriori: apriori)
  @probabilities[ probability.key ] = probability 
end

#compute(key) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/newral/bayes.rb', line 15

def compute( key )
  probability = if @probabilities[key]
    @probabilities[key]
  elsif key.start_with?("!") && @probabilities[key.sub("!","")]
    !@probabilities[key.sub("!",'')]
  elsif key.match('\|')
    key,apriori=key.split("|")
    compute("#{apriori}|#{key}")*compute(key)/compute(apriori)
  else
    apriori = @probabilities.keys.find{|p| p.split("|")[0]==key && !p.split("|")[1].match('!') }
    if apriori
      apriori = apriori.split("|")[1]
      compute("#{key}|#{apriori}")*compute(apriori)+compute("#{key}|!#{apriori}")*compute("!#{apriori}")
    else 
      puts "not found #{key}"
    end
  end
  @probabilities[ probability.key ] = probability
  probability
end