bbn

package module
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2024 License: MIT Imports: 12 Imported by: 1

README

BBN

Test status Go Report Card Go Reference GitHub

Bayesian Belief Network CLI/TUI tool and Go module.

screenshot

Features

  • Visualize, query and explore networks in the interactive TUI app bbni.
  • Supports decision networks (aka influence diagrams), including sequential decisions.
  • Provides logic nodes for logic inference in addition to probabilistic inference.
  • Train and query networks from the command line with bbn.
  • Human-readable YAML format for networks, as well as BIF-XML.
  • Plenty of examples with introductory text, shown in-app.

Installation

Command line tools

Pre-compiled binaries for Linux, Windows and MacOS are available in the Releases.

Alternatively, install the latest development versions of bbn and bbni using Go:

go install github.com/mlange-42/bbn/cmd/bbn@main
go install github.com/mlange-42/bbn/cmd/bbni@main
Library

⚠️ Please be aware that the bbn Go module is still under development and highly unstable.

Add BBN to a Go project:

go get github.com/mlange-42/bbn

Usage

Command line tools

Try the famous sprinkler example:

bbni _examples/bbn/sprinkler.yml

Same example with the command line tool, given some evidence:

bbn inference _examples/bbn/sprinkler.yml -e Rain=no,GrassWet=yes

Train a network from data:

bbn train _examples/bbn/fruits-untrained.yml _examples/bbn/fruits.csv

Also try the other examples in folder _examples. Run them with bbni and play around, but also view their .yml files to get an idea how to create Bayesian Networks.

Library

⚠️ Please be aware that the bbn Go module is still under development and highly unstable.

See the examples in the API reference.

License

This project is distributed under the MIT license.

Documentation

Overview

Package bbn provides a Bayesian Belief Network implementation.

Example (Sprinkler)
package main

import (
	"fmt"

	"github.com/mlange-42/bbn"
)

func main() {
	variables := []bbn.Variable{
		{Name: "Rain", Outcomes: []string{"yes", "no"}},
		{Name: "Sprinkler", Outcomes: []string{"yes", "no"}},
		{Name: "GrassWet", Outcomes: []string{"yes", "no"}},
	}

	factors := []bbn.Factor{
		{
			For: "Rain",
			Table: []float64{
				// rain+, rain-
				0.2, 0.8,
			},
		},
		{
			For:   "Sprinkler",
			Given: []string{"Rain"},
			Table: []float64{
				// yes   no
				0.01, 0.99, // rain+
				0.2, 0.8, // rain-
			},
		},
		{
			For:   "GrassWet",
			Given: []string{"Rain", "Sprinkler"},
			Table: []float64{
				//   yes   no
				0.99, 0.01, // rain+, sprikler+s
				0.8, 0.2, // rain+, sprikler-
				0.9, 0.1, // rain-, sprikler+
				0.0, 1.0, // rain-, sprikler-
			},
		},
	}

	net, err := bbn.New("Sprinkler", "", variables, factors)
	if err != nil {
		panic(err)
	}

	evidence := map[string]string{
		"GrassWet": "yes",
		"Rain":     "no",
	}
	query := []string{
		"Sprinkler",
	}

	result, _, err := net.SolveQuery(evidence, query, false)
	if err != nil {
		panic(err)
	}

	fmt.Println(result)
}
Output:

map[Sprinkler:[1 0]]

Index

Examples

Constants

View Source
const (
	ChanceNodeType   = "nature"
	DecisionNodeType = "decision"
	UtilityNodeType  = "utility"
)

Variables

This section is empty.

Functions

func ToYAML

func ToYAML(network *Network) ([]byte, error)

Types

type Factor added in v0.5.0

type Factor struct {
	For   string    // Primary variable of the factor.
	Given []string  `yaml:",omitempty"` // Names of dependency variables, i.e. parents.
	Table []float64 `yaml:",omitempty"` // Flat representation of the factor's table.
	// contains filtered or unexported fields
}

Factor definition, encoding a conditional probability or utility table.

func (*Factor) Row added in v0.5.0

func (f *Factor) Row(indices []int) ([]float64, bool)

Row returns a table row of the factor for the given outcome indices of given/parent variables.

The returned slice is referencing a range in the original table, so modifications affect the owning factor.

type Network

type Network struct {
	// contains filtered or unexported fields
}

Network is the primary type for solving bbn networks.

func FromBIFXML added in v0.2.0

func FromBIFXML(content []byte) (*Network, error)

FromBIFXML creates a Network from XML. See also FromFile.

func FromFile added in v0.2.0

func FromFile(path string) (*Network, error)

FromFile reads a Network from an YAML or XML file.

func FromYAML

func FromYAML(content []byte) (*Network, error)

FromBIFXML creates a Network from YAML. See also FromFile.

func New

func New(name string, info string, variables []Variable, factors []Factor) (*Network, error)

New creates a new bbn network from the given variables and factors.

func (*Network) Info added in v0.5.0

func (n *Network) Info() string

Info for the network.

func (*Network) Marginal added in v0.5.0

func (n *Network) Marginal(f *ve.Factor, variable string) ve.Factor

Marginal calculates marginal probabilities from a factor for a variable.

func (*Network) Name added in v0.2.0

func (n *Network) Name() string

Name of the network.

func (*Network) Normalize added in v0.5.0

func (n *Network) Normalize(f *ve.Factor) ve.Factor

Normalize a factor.

func (*Network) NormalizeUtility added in v0.5.0

func (n *Network) NormalizeUtility(utility *ve.Factor, probs *ve.Factor) ve.Factor

NormalizeUtility normalizes utility factor by dividing it by a probability factor.

func (*Network) Rearrange added in v0.5.0

func (n *Network) Rearrange(f *ve.Factor, variables []string) ve.Factor

Rearrange a factor for the given variable order.

func (*Network) SolvePolicies added in v0.5.0

func (n *Network) SolvePolicies(stepwise bool) (map[string]Factor, error)

SolvePolicies solves and inserts policies for decisions, using variable elimination.

Returns a map of policies for each decision variable, by variable name.

func (*Network) SolveQuery added in v0.5.0

func (n *Network) SolveQuery(evidence map[string]string, query []string, ignorePolicies bool) (map[string][]float64, *ve.Factor, error)

SolveQuery solves a query, using variable elimination.

Returns a map of normalized marginal probabilities for each query variable, by variable name. Further, it returns the resulting factor containing the query variables.

func (*Network) SolveUtility added in v0.5.0

func (n *Network) SolveUtility(evidence map[string]string, query []string, utilityVar string, ignorePolicies bool) (*ve.Factor, error)

SolveUtility solves utility, using variable elimination.

Argument utilityVar can be used to solve only the utility for a certain variable. With utilityVar set to an empty sting (""), the total utility is solved.

If there is a variable for total utility, defined by having utility variables as parents, utility nodes are weighted according to the total utility variable's factor.

Returns a factor for utility, containing the query variables.

func (*Network) ToEvidence added in v0.5.0

func (n *Network) ToEvidence(variable string, value string) ([]float64, error)

ToEvidence converts a string variable/value pair to marginal probabilities for the evidence variable.

As an example, say we have a variable with outcomes [yes, no]. Given evidence "yes" (index 0): we get the following probabilities: [1, 0].

func (*Network) TotalUtilityIndex added in v0.5.0

func (n *Network) TotalUtilityIndex() int

TotalUtilityIndex return the index of the total utility node. -1 if none.

func (*Network) Variables added in v0.5.0

func (n *Network) Variables() []Variable

Variables of the network.

type Trainer

type Trainer struct {
	// contains filtered or unexported fields
}

Trainer is a utility type to train a Network.

func NewTrainer

func NewTrainer(net *Network) Trainer

NewTrainer creates a new Trainer for the given Network.

func (*Trainer) AddSample

func (t *Trainer) AddSample(sample []int, utility []float64)

AddSample adds a training sample. Order of values in the sample is the same as the order in which nodes were passed into the Network constructor.

func (*Trainer) UpdateNetwork

func (t *Trainer) UpdateNetwork() (*Network, error)

UpdateNetwork applies the training to the network, and returns a pointer to the original network.

type Variable added in v0.5.0

type Variable struct {
	Name     string      // Name of the variable.
	NodeType ve.NodeType // Node type of the variable.
	Outcomes []string    // Possible outcomes.
	Position [2]int      // Position in bbni visualization, in terminal cells.
	Color    string      // Name of the node color in bbni visualization.
	Factor   *Factor     // Don't set this, it is initialized when constructing the network.
}

Variable definition for creating a Network.

Directories

Path Synopsis
benchmark module
cmd
bbn
BBN's command line interface.
BBN's command line interface.
bbni
BBN's interactive terminal app.
BBN's interactive terminal app.
internal
tui
Package logic provides shortcuts to create factors/CPTs for logic operations.
Package logic provides shortcuts to create factors/CPTs for logic operations.
Package ve provides low-level access to variable elimination and factor operations in general.
Package ve provides low-level access to variable elimination and factor operations in general.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL