Class: MiniPGM::TabularCPD

Inherits:
Object
  • Object
show all
Defined in:
lib/mini_pgm/tabular_cpd.rb

Overview

Represents a tabular Conditional Probability Distribution (CPD)

The CPD defines the probabilities of particular outcomes for a variable, given observations of the variables that it is dependent on (i.e. the evidence).

For example, assuming the variable ‘Cancer’ is dependent on ‘Pollution’ and ‘Smoker’, each of which have two outcomes. Then if ‘Cancer’ also has two outcomes, then the string representation of the table could look like this:

+-----------+-------------+-------------+-------------+-------------+
| Smoker    | Smoker_0    | Smoker_0    | Smoker_1    | Smoker_1    |
+-----------+-------------+-------------+-------------+-------------+
| Pollution | Pollution_0 | Pollution_1 | Pollution_0 | Pollution_1 |
+-----------+-------------+-------------+-------------+-------------+
| Cancer_0  | 0.03        | 0.05        | 0.001       | 0.02        |
+-----------+-------------+-------------+-------------+-------------+
| Cancer_1  | 0.97        | 0.95        | 0.999       | 0.98        |
+-----------+-------------+-------------+-------------+-------------+

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(variable, evidence, data) ⇒ TabularCPD

Returns a new instance of TabularCPD.

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mini_pgm/tabular_cpd.rb', line 29

def initialize(variable, evidence, data)
  expected_rows = variable.cardinality
  raise ArgumentError, "wrong number of rows; expected #{expected_rows}" unless data.length == expected_rows

  expected_cols = combinations(evidence)
  data.each.with_index do |row, index|
    raise ArgumentError, "wrong number of columns in row #{index}; expected #{expected_cols}" \
      unless row.length == expected_cols
  end

  @variable = variable
  @evidence = evidence
  @data = data
end

Instance Attribute Details

#evidenceObject (readonly)

Returns the value of attribute evidence.



27
28
29
# File 'lib/mini_pgm/tabular_cpd.rb', line 27

def evidence
  @evidence
end

#variableObject (readonly)

Returns the value of attribute variable.



27
28
29
# File 'lib/mini_pgm/tabular_cpd.rb', line 27

def variable
  @variable
end

Instance Method Details

#to_sObject



44
45
46
# File 'lib/mini_pgm/tabular_cpd.rb', line 44

def to_s
  MiniPGM::Printer.print(header(@evidence) + body(@data, @variable.label))
end