高斯混合模型matlab代码不用函数
时间: 2023-05-28 10:07:29 浏览: 119
高斯混合模型的matlab代码
以下是一个简单的高斯混合模型的matlab代码,其中使用了EM算法来估计参数。
```
clear all;
close all;
clc;
% 生成数据
mu1 = [1 2];
mu2 = [4 6];
sigma1 = [1 0.5; 0.5 2];
sigma2 = [3 0.5; 0.5 1];
n = 500;
x1 = mvnrnd(mu1, sigma1, n);
x2 = mvnrnd(mu2, sigma2, n);
X = [x1; x2];
% 初始化参数
k = 2;
[n, d] = size(X);
pi = ones(1, k) / k;
mu = [mean(x1); mean(x2)];
sigma = cat(3, cov(x1), cov(x2));
% EM算法迭代
for iter = 1:50
% E步骤
gamma = zeros(n, k);
for j = 1:k
gamma(:, j) = pi(j) * mvnpdf(X, mu(j, :), sigma(:, :, j));
end
gamma = gamma ./ sum(gamma, 2);
% M步骤
nk = sum(gamma, 1);
pi = nk / n;
for j = 1:k
mu(j, :) = (gamma(:, j)' * X) / nk(j);
sigma(:, :, j) = (X - mu(j, :))' * diag(gamma(:, j)) * (X - mu(j, :)) / nk(j);
end
% 计算似然值
llh(iter) = sum(log(sum(bsxfun(@times, pi, mvnpdf(X, mu, sigma)))));
end
% 绘制结果
figure;
plot(llh, 'LineWidth', 2);
xlabel('Iteration');
ylabel('Log-likelihood');
title('EM for Gaussian Mixture Model');
figure;
scatter(x1(:, 1), x1(:, 2), 'r', 'filled'); hold on;
scatter(x2(:, 1), x2(:, 2), 'b', 'filled');
scatter(mu(:, 1), mu(:, 2), 'k', 'filled', 'LineWidth', 2);
legend('Class 1', 'Class 2', 'Cluster Centers');
xlabel('x_1');
ylabel('x_2');
title('Gaussian Mixture Model Clustering');
```
阅读全文