github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/stat/sampleuv/example_burnin_test.go (about)

     1  // Copyright ©2015 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sampleuv_test
     6  
     7  import (
     8  	"github.com/jingcheng-WU/gonum/stat/distuv"
     9  	"github.com/jingcheng-WU/gonum/stat/sampleuv"
    10  )
    11  
    12  type ProposalDist struct {
    13  	Sigma float64
    14  }
    15  
    16  func (p ProposalDist) ConditionalRand(y float64) float64 {
    17  	return distuv.Normal{Mu: y, Sigma: p.Sigma}.Rand()
    18  }
    19  
    20  func (p ProposalDist) ConditionalLogProb(x, y float64) float64 {
    21  	return distuv.Normal{Mu: y, Sigma: p.Sigma}.LogProb(x)
    22  }
    23  
    24  func ExampleMetropolisHastings_burnin() {
    25  	n := 1000    // The number of samples to generate.
    26  	burnin := 50 // Number of samples to ignore at the start.
    27  	var initial float64
    28  	// target is the distribution from which we would like to sample.
    29  	target := distuv.Weibull{K: 5, Lambda: 0.5}
    30  	// proposal is the proposal distribution. Here, we are choosing
    31  	// a tight Gaussian distribution around the current location. In
    32  	// typical problems, if Sigma is too small, it takes a lot of samples
    33  	// to move around the distribution. If Sigma is too large, it can be hard
    34  	// to find acceptable samples.
    35  	proposal := ProposalDist{Sigma: 0.2}
    36  
    37  	samples := make([]float64, n)
    38  	mh := sampleuv.MetropolisHastings{Initial: initial, Target: target, Proposal: proposal, BurnIn: burnin}
    39  	mh.Sample(samples)
    40  }