Assignment 05 solution

Disclaimer: Dieser Thread wurde aus dem alten Forum importiert. Daher werden eventuell nicht alle Formatierungen richtig angezeigt. Der ursprüngliche Thread beginnt im zweiten Post dieses Threads.

Assignment 05 solution
Since some asked, here is my solution (in Scala) for Assignment 05.

Remark: That code is two years old; please don’t ask me what went through my head when I named [m]querynodes[/m] and [m]queryvalues[/m]… :smiley:

def queryScala(network:Network,node:Node,evidence:List[(Node,Boolean)]) : Double = {
    val allnodes = network.getNodes.toList
    val querynodes = evidence.map(_._1)
    val queryvalues = evidence.map(_._2)
    val hiddens = allnodes.filter(n => n!=node && !querynodes.contains(n))

    /** Takes a list of nodes and returns the list of all possible boolean assignments
    */
    def allPossibleValuesOf(ns : List[Node]) : List[List[scala.Boolean]] =
      ns.foldRight[List[List[scala.Boolean]]](List(Nil))((n, ls) => ls.map(l => true :: l) ::: ls.map(l => false :: l))

    // for all possible assigments to the query variables... (yields the non-normalized distribution)
    val predistribution = List(true,false).map(value => {
      // for all possible assignments to the hidden variables... (these will be summed up)
      allPossibleValuesOf(hiddens).map(hiddenvalues => {

        /** Returns the boolean value of node n given the current
          * assignments to hidden/query-variables
          * @return true or false
          */
        def getValue(n : Node) : scala.Boolean = if (n == node) value // the queried node is always true
          else if (querynodes contains n) queryvalues(querynodes indexOf n) // n is a query node; look up in queryvalues
          else hiddenvalues(hiddens indexOf n) // n is a hidden variable; look up in hiddenvalues

        /** Returns the actual conditional probability of n given the
          * current assignment to the parents
          * @return P(+/-n|parents(n))
          */
        def prob(n : Node) : Double = {
          val parentvalues = n.parents.map(getValue) // get the current assignment for all parent nodes
          val p = n.getProb(parentvalues.map(b => toJava(b)).toArray/*(new Array(parentvalues.length)*/) // get the probability for n
          if(getValue(n)) p else 1.0 - p // return p or (1-p), depending on the value of n
        }

        allnodes.map(prob).foldLeft(1.0)((a,b) => a*b) // we multiply all the individual conditional probabilities
      }).sum // ...and sum over all assignments to the hidden variables
    })

    val alpha = 1.0 / predistribution.sum

    val distribution = predistribution.map(_ * alpha)

    distribution.head
  }