Project4 Shiny the 2D normal distribution

eulerwang

2017/1/6

2D normal distribution Pho relationship instruction

  1. set the pho parameter

  2. view the 2d normal distribution

  3. because the data is generated by gibbs sampling process , so the pho parameter may be different from the input.

gibbs sampling process

The Gibbs sampler was developed by Geman & Geman (1984). Let Zi = (Xi, Yi) be a Markov chain. The Gibbs sampler can be used to generate specific multivariate distributions. Let f(x, y) be a given joint density and f(x|y) and f(y|x) to be conditional densities. The Gibbs sampling algorithm is given by

  1. Generate Z0 = (X0, Y0),i = 1
  2. Generate Xi ∼ f(xi|Yi−1 = yi−1)
  3. Generate Yi ∼ f(yi|Xi = xi)
  4. Set i = i + 1 and goto step 2.

gibbs sampling process

Here is the gibbs Sampling process demo .

gibbs<-function (n, rho) 
{
  mat <- matrix(ncol = 2, nrow = n)
  x <- 0
  y <- 0
  mat[1, ] <- c(x, y)
  for (i in 2:n) {
    x <- rnorm(1, rho * y, (1 - rho^2))
    y <- rnorm(1, rho * x,(1 - rho^2))
    mat[i, ] <- c(x, y)
  }
  mat
}

gibbs(10,0.5)
##             [,1]        [,2]
##  [1,]  0.0000000  0.00000000
##  [2,] -0.6923221 -0.81256484
##  [3,] -1.0605809 -0.83585698
##  [4,] -0.5947733 -0.30375852
##  [5,]  0.1722685 -0.06998336
##  [6,]  0.1215482 -0.26397551
##  [7,]  0.2210253 -0.29714731
##  [8,]  0.1412832 -0.45869485
##  [9,]  0.3438846 -0.05165075
## [10,]  0.9823960  1.91443414

plot the 2d normal distribution data using the package ‘psych’

library(psych)

bvn <- as.data.frame(gibbs(10000,0.1))

scatter.hist(x=bvn$V1, y=bvn$V2, density=TRUE, ellipse=TRUE)