基于核密度估计的PDF近似优化计算时间 [英] Optimize computation time for PDF approximation based on Kernel Density Estimation

查看:127
本文介绍了基于核密度估计的PDF近似优化计算时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码可根据核估计公式找到矢量的pdf近似值:
我在下面的代码中实现了此公式(请参见上一个问题).但是,该代码需要很长时间才能运行(使用了两个循环).您能看到下面的代码,并帮助我使其更快吗?

I have a code to find the pdf's approximation of a vector based on the formula for kernel estimation:
I implemented this formula in the code below (see previous question). However, that code takes long time to run (two loops are used). Could you see the below code and help me to make it faster?

这是代码:

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));

推荐答案

您可以摆脱这两个讨厌的 nested loops,然后使用硬编码的sigma进行大减vectorized solution-

You can get rid of both of those nasty nested loops and then use the hardcoded sigma to have a mega-reduced vectorized solution -

pdf_est = sum(1./(sqrt(2*pi))*exp(-bsxfun(@minus,[0:z-1]',data).^2/2),2)

或者,如果您想灵活地使用sigma,请使用此-

Or if you would like to have the flexibility to have sigma around, use this -

sum(1./(sqrt(2*pi)*sigma)*exp(-bsxfun(@minus,[0:z-1]',data).^2/(2*sigma^2)),2)

这真的是全部!

快速测试将其用于通过 10x 来加快原始代码的速度!

Quick tests put this to speedup the original code by 10x!

这篇关于基于核密度估计的PDF近似优化计算时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆