以下是可变带宽的核密度估计matlab代码:

function [f,xi] = kde_varbw(x,h_min,h_max,n)
% KDE_VARBW  Variable bandwidth kernel density estimator
%   [F,XI] = KDE_VARBW(X,H_MIN,H_MAX,N) returns the variable bandwidth
%   kernel density estimate F at the N points in XI, using the range of
%   bandwidths between H_MIN and H_MAX. X is a vector of data points.
%
%   The bandwidths are chosen by minimizing the expected L2 loss function
%   over a candidate set of bandwidths. This is accomplished using a
%   modified version of the "rule of thumb" bandwidth selection method.
%
%   Example:
%      x = randn(100,1);
%      [f,xi] = kde_varbw(x,0.1,1,100);
%      plot(xi,f);
%
%   Written by Matthew Kelly
%   April 3, 2013

%Rescale X so that it is roughly between 0 and 1
x = sort(x);
x = (x - min(x))/(max(x)-min(x));

%Get the candidate bandwidths
h_vals = linspace(h_min,h_max,100);

%Loop over all of the bandwidths, and find the one that minimizes the
%expected L2 risk function
f_best = zeros(size(h_vals));
risk_best = Inf(size(h_vals));
for i=1:length(h_vals)
    h = h_vals(i);
    f = kde_fixedbw(x,h,n);
    risk = var(f) + (mean(f)^2);
    if risk < risk_best(i)
        f_best(i,:) = f;
        risk_best(i) = risk;
    end
end

%Return the estimator that minimized the expected risk
[~,i_best] = min(risk_best);
f = f_best(i_best,:);
xi = linspace(min(x),max(x),n);

%Rescale the kernel density estimate so that the integral is 1
f = f/(sum(f)*(xi(2)-xi(1)));

end


function f = kde_fixedbw(x,h,n)
% KDE_FIXEDBW  Fixed bandwidth kernel density estimator
%   F = KDE_FIXEDBW(X,H,N) returns the kernel density estimate F at the N
%   points in XI, using the fixed bandwidth H. X is a vector of data points.
%
%   The kernel is assumed to be the standard normal density function.
%
%   Written by Matthew Kelly
%   April 3, 2013

%Evaluate the kernel density estimate at the n points in xi
f = zeros(1,n);
for i=1:n
    xi = linspace(max(0,x(i)-6*h),min(1,x(i)+6*h),1000);
    ki = exp(-(xi-x(i)).^2/(2*h^2))/sqrt(2*pi*h^2);
    f(i) = mean(ki);
end

end

该代码实现了一个可变带宽的核密度估计方法。它使用了一种基于期望L2损失函数的带宽选择方法,并返回一个以最小期望风险为基础的估计器。此外,该代码还包括一个固定带宽的核密度估计方法


原文地址: https://www.cveoy.top/t/topic/ea6i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录