]> Creatis software - CreaPhase.git/blob - octave_packages/econometrics-1.0.8/kernel_optimal_bandwidth.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / econometrics-1.0.8 / kernel_optimal_bandwidth.m
1 # Copyright (C) 2007 Michael Creel <michael.creel@uab.es>
2 #
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.
7 #
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.
12 #
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/>.
15
16 # kernel_optimal_bandwidth: find optimal bandwith doing leave-one-out cross validation
17 # inputs:
18 #       * data: data matrix
19 #       * depvar: column vector or empty ("").
20 #               If empty, do kernel density, orherwise, kernel regression
21 #       * kernel (optional, string) the kernel function to use
22 # output:
23 #       * h: the optimal bandwidth
24
25 function bandwidth = kernel_optimal_bandwidth(data, depvar, kernel)
26
27         if (nargin < 2) error("kernel_optimal_bandwidth: 3 arguments required"); endif
28         if (nargin < 3) kernel = "__kernel_epanechnikov"; endif
29
30         do_density = false;
31         if isempty(depvar) do_density = true; endif;
32
33         # SA controls
34         ub = 3;
35         lb = -5;
36         nt = 1;
37         ns = 1;
38         rt = 0.05;
39         maxevals = 50;
40         neps = 5;
41         functol = 1e-2;
42         paramtol = 1e-3;
43         verbosity = 0;
44         minarg = 1;
45         sa_control = { lb, ub, nt, ns, rt, maxevals, neps, functol, paramtol, verbosity, 1};
46
47         # bfgs controls
48         bfgs_control = {10};
49
50         if do_density
51                 bandwidth = samin("kernel_density_cvscore", {1, data, kernel}, sa_control);
52                 bandwidth = bfgsmin("kernel_density_cvscore", {bandwidth, data, kernel}, bfgs_control);
53         else
54                 bandwidth = samin("kernel_regression_cvscore", {1, data, depvar, kernel}, sa_control);
55                 bandwidth = bfgsmin("kernel_regression_cvscore", {bandwidth, data, depvar, kernel}, bfgs_control);
56         endif
57         bandwidth = exp(bandwidth);
58 endfunction