1 # Copyright (C) 2007 Michael Creel <michael.creel@uab.es>
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; If not, see <http://www.gnu.org/licenses/>.
16 # kernel_optimal_bandwidth: find optimal bandwith doing leave-one-out cross validation
19 # * depvar: column vector or empty ("").
20 # If empty, do kernel density, orherwise, kernel regression
21 # * kernel (optional, string) the kernel function to use
23 # * h: the optimal bandwidth
25 function bandwidth = kernel_optimal_bandwidth(data, depvar, kernel)
27 if (nargin < 2) error("kernel_optimal_bandwidth: 3 arguments required"); endif
28 if (nargin < 3) kernel = "__kernel_epanechnikov"; endif
31 if isempty(depvar) do_density = true; endif;
45 sa_control = { lb, ub, nt, ns, rt, maxevals, neps, functol, paramtol, verbosity, 1};
51 bandwidth = samin("kernel_density_cvscore", {1, data, kernel}, sa_control);
52 bandwidth = bfgsmin("kernel_density_cvscore", {bandwidth, data, kernel}, bfgs_control);
54 bandwidth = samin("kernel_regression_cvscore", {1, data, depvar, kernel}, sa_control);
55 bandwidth = bfgsmin("kernel_regression_cvscore", {bandwidth, data, depvar, kernel}, bfgs_control);
57 bandwidth = exp(bandwidth);