Likelihood Weighting


LIKELIHOOD-WEIGHTING(bn, query, numSamples)
    weighted_set ← {} // A map that stores (sample, count) pairs

    for s=1...numSamples

        weight ← 1
        sample ← {}
        for node Xi in bn

            if Xi is an evidence variable
	        assign Xi to its observed value

                //How likely is the evidence given what we've sampled so far?
                weight ← weight * p(Xi | parents(Xi))
            else

                value ← randomly sample from p(Xi | parents(Xi))
                if Xi is a query variable
                    sample.append(value)
                end
            end
        end    

        //Sample now contains the sampled values for all of the query variables
        //The sampled values are guaranteed to be consistent with the evidence
        weighted_set{sample} += weight 
    end

    return weighted_set.normalize()
end