修改以下错误代码library(MASS) set.seed(123) n <- 1000 mu1 <- c(0,4) mu2 <- c(-2,0) Sigma1 <- matrix(c(3,0,0,0.5),nr=2,nc=2) Sigma2 <- matrix(c(1,0,0,2),nr=2,nc=2) phi <- c(0.6,0.4) X <- matrix(0,nr=2,nc=n) for (i in 1:n) { if (runif(1)<=phi[1]) { X[,i] <- mvrnorm(1,mu=mu1,Sigma=Sigma1) }else{ X[,i] <- mvrnorm(1,mu=mu2,Sigma=Sigma2) } } EM_GMM <- function(X, k){ n <- ncol(X) d <- nrow(X) w <- rep(1/k, k) mu <- matrix(rnorm(kd, mean(X), sd(X)), nrow=k, ncol=d) sigma <- array(aperm(array(rnorm(kdd), dim=c(k,d,d)), c(2,3,1)), dim=c(d,d,k)) R <- numeric(kn) for (iter in 1:100){ # E步 for (i in 1:k){ R[(i-1)n+1:in]<- w[i] * dnorm(X, mean=mu[i,], sd=sigma[,,i]) } R <- matrix(R, nrow=n, byrow=TRUE) R <- R / rowSums(R) # M步 Nk <- colSums(R) # 每个分量的权重 w <- Nk / n # 均值 for (i in 1:k){ mu[i,] <- colSums(R[,i] * X) / Nk[i] # 均值 sigma[,,i] <- (t(X) %*% (R[,i] * X)) / Nk[i] - mu[i,] %*% t(mu[i,]) # 协方差矩阵 } } list(w=w, mu=mu, sigma=sigma) } result <- EM_GMM(X, 2) xgrid <- seq(min(X[1,]), max(X[1,]), length.out=100) ygrid <- seq(min(X[2,]), max(X[2,]), length.out=100) z <- outer(xgrid, ygrid, function(x,y) { z <- numeric(length(x)) for (i in 1:nrow(result$mu)){ z <- z + result$w[i] * dnorm(c(x, y), mean=result$mu[i,], sd=sqrt(result$sigma[1,1,i])) } z }) contour(xgrid, ygrid, z, nlev=10, color.palette=heat.colors, main="Two-component GMM Contours")
时间: 2023-06-04 11:06:39 浏览: 449
以下是修改后的代码:
library(MASS)
set.seed(123)
n <- 1000
mu1 <- c(0,4)
mu2 <- c(-2,0)
Sigma1 <- matrix(c(3,0,0,0.5),nr=2,nc=2)
Sigma2 <- matrix(c(1,0,0,2),nr=2,nc=2)
phi <- c(0.6,0.4)
X <- matrix(0,nr=2,nc=n)
for (i in 1:n) {
if (runif(1) <= phi[1]) {
X[,i] <- mvrnorm(1,mu=mu1,Sigma=Sigma1)
} else {
X[,i] <- mvrnorm(1,mu=mu2,Sigma=Sigma2)
}
}
EM_GMM <- function(X, k){
n <- ncol(X)
d <- nrow(X)
kdd <- k*d*d # 计算数组中元素个数
kd <- k*d # 计算数组中向量元素个数
w <- rep(1/k, k)
mu <- matrix(rnorm(k*d, mean(X), sd(X)), nrow=k, ncol=d)
sigma <- array(aperm(array(rnorm(kdd), dim=c(k,d,d)), c(2,3,1)), dim=c(d,d,k))
R <- numeric(k*n)
for (iter in 1:100){
# 更新 R
for (j in 1:k){
R[(j-1)*n+1:j*n] <- w[j] * dmnorm(X, mu[j,], sigma[,,j])
}
R <- R / matrix(rowSums(matrix(R,nrow=k)), nrow=n, ncol=k, byrow=T)
# 更新 w, mu, sigma
w <- colSums(R) / n
for (j in 1:k){
mu[j,] <- colSums(X * matrix(R[,j], nrow=n, ncol=1)) / sum(R[,j])
sigma[,,j] <- (t(X-mu[j,]) %*% (X-mu[j,]) * matrix(R[,j], nrow=n, ncol=n)) / sum(R[,j])
}
}
return(list(w=w, mu=mu, sigma=sigma))
}
EM_GMM(X, 2) # 测试函数是否正确
阅读全文