Created
May 30, 2017 13:51
-
-
Save benilton/b7b59e86ce66264f7bc8221426ca89ea to your computer and use it in GitHub Desktop.
Algoritmo EM - Exemplo em Mistura Finita
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Gerando dados | |
set.seed(1) | |
y1 = rnorm(20, 2.5, 1.25) | |
y2 = rnorm(20, 5, 1.25) | |
Y = c(y1, y2) | |
data(faithful) | |
plot(faithful$waiting, faithful$eruptions) | |
Y = faithful$eruptions | |
mu1 = 1 | |
mu2 = 7 | |
lambda = .8 | |
sigma2 = 2 | |
LL = function(Y, mu1, mu2, sigma2, lambda){ | |
dens1 = (1-lambda)*dnorm(Y, mu1, sqrt(sigma2)) | |
dens2 = lambda*dnorm(Y, mu2, sqrt(sigma2)) | |
sum(log(dens1+dens2)) | |
} | |
erro = 1 | |
i = 1 | |
plot(1, xlim=c(1, 20), ylim=c(-340, 0), type='n') | |
while (erro > 1e-6 & i < 1000){ | |
LL_ant = LL(Y, mu1, mu2, sigma2, lambda) | |
message("Iteracao: ", i) | |
dens1 = (1-lambda)*dnorm(Y, mu1, sqrt(sigma2)) | |
dens2 = lambda*dnorm(Y, mu2, sqrt(sigma2)) | |
z = dens2/(dens1+dens2) | |
plot(faithful$waiting, faithful$eruptions, col = (z>.5)+1, pch=19) | |
Sys.sleep(1) | |
mu1_ant = mu1 | |
mu2_ant = mu2 | |
mu1 = sum((1-z)*Y)/sum(1-z) | |
mu2 = sum(z*Y)/sum(z) | |
lambda = mean(z) | |
sigma2 = (1-lambda)*sum((1-z)*(Y-mu1)^2)/sum(1-z) + lambda*sum(z*(Y-mu2)^2)/sum(z) | |
i = i+1 | |
LL_nova = LL(Y, mu1, mu2, sigma2, lambda) | |
erro = abs(LL_nova-LL_ant) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment