コード例 #1
0
    mu0 = pt[0]
    mu1 = pt[1]
    term1 = p * np.exp(-(observations - mu1)**2 / 2)
    term0 = (1.0 - p) * np.exp(-(observations - mu0)**2 / 2)
    res = term1 / (term1 + term0)
    # output must be a 1d list or array in order to create a PythonFunction
    return res.reshape(-1)


nor0posterior = ot.PythonFunction(2 + N, 2, nor0post)
nor1posterior = ot.PythonFunction(2 + N, 2, nor1post)
zposterior = ot.PythonFunction(2 + N, N, zpost)

# We can now construct the Gibbs algorithm
initialState = [0.0] * (N + 2)
sampler0 = ot.RandomVectorMetropolisHastings(ot.RandomVector(ot.Normal()),
                                             initialState, [0], nor0posterior)
sampler1 = ot.RandomVectorMetropolisHastings(ot.RandomVector(ot.Normal()),
                                             initialState, [1], nor1posterior)
big_bernoulli = ot.ComposedDistribution([ot.Bernoulli()] * N)
sampler2 = ot.RandomVectorMetropolisHastings(ot.RandomVector(big_bernoulli),
                                             initialState, range(2, N + 2),
                                             zposterior)
gibbs = ot.Gibbs([sampler0, sampler1, sampler2])

# Run the Gibbs algorithm
s = gibbs.getSample(10000)

# Extract the relevant marginals: the first (:math:`mu_0`) and the second (:math:`\mu_1`).
posterior_sample = s[:, 0:2]
mean = posterior_sample.computeMean()
stddev = posterior_sample.computeStandardDeviation()
コード例 #2
0
#! /usr/bin/env python

import openturns as ot
import openturns.testing as ott

ot.TESTPREAMBLE()

randomVector = ot.RandomVector(ot.Normal())
initialState = [0.0]
sampler = ot.RandomVectorMetropolisHastings(randomVector, initialState)
sampler.setBurnIn(20)
sampler.setThinning(2)
x = sampler.getSample(10000)
mean = x.computeMean()
stddev = x.computeStandardDeviation()
print(mean, stddev)
#ott.assert_almost_equal(mean, [0.824453, -0.0215115])
#ott.assert_almost_equal(stddev, [0.00197192, 0.968657])

# with link function
slf = ot.SymbolicFunction(['x'], ['0.0', '0.1'])
sampler = ot.RandomVectorMetropolisHastings(
    randomVector, initialState, [0], slf)
x = sampler.getSample(10000)
mean = x.computeMean()
stddev = x.computeStandardDeviation()
print(mean, stddev)
ott.assert_almost_equal(mean, [0.000605902])
ott.assert_almost_equal(stddev, [0.0997537])