I am using Gaussian kernel to estimate a pdf of a data based on the equation
where K(.) is Gaussian kernel, data is a given vector. z is bin from 1 to 256. size of bin is 1.
我是通过matlab代码实现的。然而,结果显示我的 pdf 估计(蓝色)的幅度与数据的真实 pdf 不相似。您能查看我的代码并给我一些关于我的代码的评论吗?
MATLAB代码
function pdf_est=KDE()
close all;
%%Random values of 20 pixels, range=[1 256]
data=randi([1 256],1,20);
%% Estimate histogram%%%%%
pdf_est=zeros(1,256);
z=256;
for i=1:z
for j=1:length(data)
pdf_est(i)=pdf_est(i)+Gaussian(i-data(j));
end
end
%% Plot real histogram 1 to 256; binsize=1;
hold on
plot(imhist(uint8(data))./length(data),'r');
%% Plot histogram estimation
plot(pdf_est./length(data),'b');
hold off
function K=Gaussian(x)
sigma=1;
K=1./(sqrt(2*pi)*sigma)*exp(-x^2./(2*sigma^2));
RESULT BLUE is my result and RED is real pdf
你有两个问题:
- 蓝色和红色图之间的 1 单位位移。
- 蓝色的尖刺比红色的尖刺更宽、更矮。
如何解决每个问题:
-
这是由于两者之间可能存在混淆造成的数据范围0,...,255 以及索引间隔1,...,256。由于您的数据表示 8 位图像,因此值应为 0,...,255(而不是 1,...,256)。您绘制的水平轴应该是 0,...,255。同样适用于i
变量在for
线。然后,由于 Matlab 索引从 1 开始,您应该使用i+1
索引时pdf_est
.
-
这是正常行为。你假设单位方差在你的内核中。要看到更高的蓝色尖峰,您可以减少sigma
使内核更窄更高。但你永远不会得到与你的数据完全相同的高度(必要的sigma
将取决于您的数据)。
事实上,你有一个高度和宽度之间的权衡, 受控制于sigma
。但重要的是,area对于任何sigma
。所以我建议绘制 CDF(面积)而不是 pdf(面积密度)。为此,绘制积累直方图和 pdf(使用cumsum http://es.mathworks.com/help/matlab/ref/cumsum.html).
代码按照1修改:
function pdf_est=KDE()
close all;
%%Random values of 20 pixels, range=[1 256]
data=randi([1 256],1,20)-1; %// changed: "-1"
%% Estimate histogram%%%%%
pdf_est=zeros(1,256);
z=256;
for i=0:z-1 %// changed_ subtracted 1
for j=1:length(data)
pdf_est(i+1)=pdf_est(i+1)+Gaussian(i-data(j)); %// changed: "+1" (twice)
end
end
%% Plot real histogram 1 to 256; binsize=1;
hold on
plot(0:255, imhist(uint8(data))./length(data),'r'); %// changed: explicit x axis
%% Plot histogram estimation
plot(0:255, pdf_est./length(data),'b'); %// changed: explicit x axis
hold off
function K=Gaussian(x)
sigma=1; %// change? Set as desired
K=1./(sqrt(2*pi)*sigma)*exp(-x^2./(2*sigma^2));
根据1和2修改代码:
function pdf_est=KDE()
close all;
%%Random values of 20 pixels, range=[1 256]
data=randi([1 256],1,20)-1; %// changed: "-1"
%% Estimate histogram%%%%%
pdf_est=zeros(1,256);
z=256;
for i=0:z-1 %// changed: subtracted 1
for j=1:length(data)
pdf_est(i+1)=pdf_est(i+1)+Gaussian(i-data(j)); %// changed: "+1" (twice)
end
end
%% Plot real histogram 1 to 256; binsize=1;
hold on
plot(0:255, cumsum(imhist(uint8(data))./length(data)),'r'); %// changed: explicit x axis
%// changed: cumsum
%% Plot histogram estimation
plot(0:255, cumsum(pdf_est./length(data)),'b'); %// changed: explicit x axis
%// changed: cumsum
hold off
function K=Gaussian(x)
sigma=1; %// change? Set as desired
K=1./(sqrt(2*pi)*sigma)*exp(-x^2./(2*sigma^2));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)