matlab 高斯混合模型代码
时间: 2023-10-01 10:11:03 浏览: 99
高斯混合模型Matlab代码
4星 · 用户满意度95%
以下是一个示例高斯混合模型的MATLAB代码:
% 生成一些数据
data = [randn(1000,2)*0.75+ones(1000,2);
randn(1000,2)*0.5-ones(1000,2)];
% 初始化高斯混合模型
num_clusters = 2;
[~, centers] = kmeans(data, num_clusters);
sigmas = repmat(eye(size(data,2)), [1 1 num_clusters]);
weights = ones(num_clusters, 1) ./ num_clusters;
% EM算法
max_iters = 10;
for iter = 1:max_iters
% Expectation步骤
for i = 1:size(data,1)
for j = 1:num_clusters
likelihood(j,i) = mvnpdf(data(i,:), centers(j,:), sigmas(:,:,j));
end
likelihood(:,i) = likelihood(:,i) .* weights;
likelihood(:,i) = likelihood(:,i) ./ sum(likelihood(:,i));
end
% Maximization步骤
for j = 1:num_clusters
weights(j) = mean(likelihood(j,:));
centers(j,:) = likelihood(j,:) * data / sum(likelihood(j,:));
sigmas(:,:,j) = zeros(size(data,2));
for i = 1:size(data,1)
sigmas(:,:,j) = sigmas(:,:,j) + likelihood(j,i) * (data(i,:)-centers(j,:)).' * (data(i,:)-centers(j,:));
end
sigmas(:,:,j) = sigmas(:,:,j) / sum(likelihood(j,:));
end
end
% 绘制结果
figure;
plot(data(:,1), data(:,2), 'k.');
hold on;
for j = 1:num_clusters
plot_gaussian_ellipsoid(centers(j,:), sigmas(:,:,j));
end
hold off;
% 绘制高斯分布椭圆形状的函数
function h = plot_gaussian_ellipsoid(mu, Sigma)
[V,D] = eig(Sigma);
t = linspace(0,2*pi);
a = (V * sqrt(D)) * [cos(t(:))'; sin(t(:))'];
b = repmat(mu', [1 size(a,2)]);
a = a + b;
h = plot(a(1,:), a(2,:), '-');
end
阅读全文