高斯分布
\quad
在数据建模时,经常会用到高斯分布模型[1,2],下面我们就使用Matlab来绘制高斯分布曲面。
\quad
另一种画法可参考:示例代码-Matlab绘制高斯分布曲面图(2)。
1. 首先,需要得到
x
o
y
xoy
xoy 平面每个交叉点的坐标。这里,我们需要使用 matlab 中的 meshgrid 函数。
2. 然后,根据高斯分布的均值以及协方差矩阵来计算每个点的概率密度。这里,我们需要使用 matlab 中的 mvnpdf 函数。
3. 最后,将计算出的交叉点的概率绘制出来,形成一个曲面。这里,我们需要使用 matlab 中的 surf 函数。
代码如下:
clear;
clc;
mu = zeros(1,2); %该高斯分布的均值向量
sigma = [0.9 0.5; 0.5 0.9]; %该高斯分布的协方差矩阵
% 第1步.
% 使用 meshgrid 函数得到xoy平面中每个交叉点的坐标,横坐标矩阵 X 、和纵坐标矩阵 Y
[X,Y] = meshgrid(-1.5:0.05:1.5);
[rows,cols] = size(X);
x = reshape(X,rows*cols,1);
y = reshape(Y,rows*cols,1);
p = [x,y]; %将每个点的横坐标矩阵 X 和纵坐标矩阵 Y 合并到一个矩阵中
% 第2步.
% 使用 mvnpdf 函数得到每个点的概率密度
z = mvnpdf(p,mu,sigma); %求得网格点上的概率密度
Z = reshape(z,rows,cols);
% 第3步.
% 使用 surf 函数画出高斯分布的曲面
figure
surf(X,Y,Z); %画曲面
此段代码的效果图如下:
此外绘制高斯曲面还可以只用 mesh, surfc 和 meshc函数,其中最后两个函数可以显示等高线。可自行运行如下代码观察效果:
surf(X,Y,Z); %画曲面
mesh(X,Y,Z); %画网格
surfc(X,Y,Z); %画曲面 ,可以显示等高线
meshc(X,Y,Z); %画网格 ,可以显示等高线
示例代码地址: https://github.com/Kai-Xuan/MyNote/blob/master/Matlab/Gaussian/gaussian_surf1.m/ [link]
参考:
1. Chen K X, Ren J Y, Wu X J, et al. Covariance Descriptors on a Gaussian Manifold and their Application to Image Set Classification[J]. Pattern Recognition, 2020: 107463. [link]
2. https://ww2.mathworks.cn/help/stats/multivariate-normal-distribution-1.html [link]