def kdensityfft(X, kernel="gau", bw="scott", weights=None, gridsize=None, adjust=1, clip=(-np.inf,np.inf), cut=3, retgrid=True): """ Rosenblatz-Parzen univariate kernel desnity estimator Parameters ---------- X : array-like The variable for which the density estimate is desired. kernel : str ONLY GAUSSIAN IS CURRENTLY IMPLEMENTED. "bi" for biweight "cos" for cosine "epa" for Epanechnikov, default "epa2" for alternative Epanechnikov "gau" for Gaussian. "par" for Parzen "rect" for rectangular "tri" for triangular bw : str, float "scott" - 1.059 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) "silverman" - .9 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) If a float is given, it is the bandwidth. weights : array or None WEIGHTS ARE NOT CURRENTLY IMPLEMENTED. Optional weights. If the X value is clipped, then this weight is also dropped. gridsize : int If gridsize is None, min(len(X), 512) is used. Note that the provided number is rounded up to the next highest power of 2. adjust : float An adjustment factor for the bw. Bandwidth becomes bw * adjust. clip : tuple Observations in X that are outside of the range given by clip are dropped. The number of observations in X is then shortened. cut : float Defines the length of the grid past the lowest and highest values of X so that the kernel goes to zero. The end points are -/+ cut*bw*{X.min() or X.max()} retgrid : bool Whether or not to return the grid over which the density is estimated. Returns ------- density : array The densities estimated at the grid points. grid : array, optional The grid points at which the density is estimated. Notes ----- Only the default kernel is implemented. Weights aren't implemented yet. This follows Silverman (1982) with changes suggested by Jones and Lotwick (1984). However, the discretization step is replaced by linear binning of Fan and Marron (1994). This should be extended to accept the parts that are dependent only on the data to speed things up for cross-validation. References ---------- :: Fan, J. and J.S. Marron. (1994) `Fast implementations of nonparametric curve estimators`. Journal of Computational and Graphical Statistics. 3.1, 35-56. Jones, M.C. and H.W. Lotwick. (1984) `Remark AS R50: A Remark on Algorithm AS 176. Kernal Density Estimation Using the Fast Fourier Transform`. Journal of the Royal Statistical Society. Series C. 33.1, 120-2. Silverman, B.W. (1982) `Algorithm AS 176. Kernel density estimation using the Fast Fourier Transform. Journal of the Royal Statistical Society. Series C. 31.2, 93-9. """ X = np.asarray(X) X = X[np.logical_and(X>clip[0], X<clip[1])] # won't work for two columns. # will affect underlying data? try: bw = float(bw) except: bw = bandwidths.select_bandwidth(X, bw, kernel) # will cross-val fit this pattern? bw *= adjust nobs = float(len(X)) # after trim # 1 Make grid and discretize the data if gridsize == None: gridsize = np.max((nobs,512.)) gridsize = 2**np.ceil(np.log2(gridsize)) # round to next power of 2 a = np.min(X)-cut*bw b = np.max(X)+cut*bw grid,delta = np.linspace(a,b,gridsize,retstep=True) RANGE = b-a #TODO: Fix this? # This is the Silverman binning function, but I believe it's buggy (SS) # weighting according to Silverman # count = counts(X,grid) # binned = np.zeros_like(grid) #xi_{k} in Silverman # j = 0 # for k in range(int(gridsize-1)): # if count[k]>0: # there are points of X in the grid here # Xingrid = X[j:j+count[k]] # get all these points # # get weights at grid[k],grid[k+1] # binned[k] += np.sum(grid[k+1]-Xingrid) # binned[k+1] += np.sum(Xingrid-grid[k]) # j += count[k] # binned /= (nobs)*delta**2 # normalize binned to sum to 1/delta #NOTE: THE ABOVE IS WRONG, JUST TRY WITH LINEAR BINNING binned = linbin(X,a,b,gridsize)/(delta*nobs) # step 2 compute FFT of the weights, using Munro (1976) FFT convention y = forrt(binned) # step 3 and 4 for optimal bw compute zstar and the density estimate f # don't have to redo the above if just changing bw, ie., for cross val #NOTE: silverman_transform is the closed form solution of the FFT of the #gaussian kernel. Not yet sure how to generalize it. zstar = silverman_transform(bw, gridsize, RANGE)*y # 3.49 in Silverman # 3.50 w Gaussian kernel f = revrt(zstar) if retgrid: return f, grid, bw else: return f, bw
def kdensityfft(X, kernel="gau", bw="scott", weights=None, gridsize=None, adjust=1, clip=(-np.inf, np.inf), cut=3, retgrid=True): """ Rosenblatz-Parzen univariate kernel desnity estimator Parameters ---------- X : array-like The variable for which the density estimate is desired. kernel : str ONLY GAUSSIAN IS CURRENTLY IMPLEMENTED. "bi" for biweight "cos" for cosine "epa" for Epanechnikov, default "epa2" for alternative Epanechnikov "gau" for Gaussian. "par" for Parzen "rect" for rectangular "tri" for triangular bw : str, float "scott" - 1.059 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) "silverman" - .9 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) If a float is given, it is the bandwidth. weights : array or None WEIGHTS ARE NOT CURRENTLY IMPLEMENTED. Optional weights. If the X value is clipped, then this weight is also dropped. gridsize : int If gridsize is None, min(len(X), 512) is used. Note that the provided number is rounded up to the next highest power of 2. adjust : float An adjustment factor for the bw. Bandwidth becomes bw * adjust. clip : tuple Observations in X that are outside of the range given by clip are dropped. The number of observations in X is then shortened. cut : float Defines the length of the grid past the lowest and highest values of X so that the kernel goes to zero. The end points are -/+ cut*bw*{X.min() or X.max()} retgrid : bool Whether or not to return the grid over which the density is estimated. Returns ------- density : array The densities estimated at the grid points. grid : array, optional The grid points at which the density is estimated. Notes ----- Only the default kernel is implemented. Weights aren't implemented yet. This follows Silverman (1982) with changes suggested by Jones and Lotwick (1984). However, the discretization step is replaced by linear binning of Fan and Marron (1994). This should be extended to accept the parts that are dependent only on the data to speed things up for cross-validation. References ---------- :: Fan, J. and J.S. Marron. (1994) `Fast implementations of nonparametric curve estimators`. Journal of Computational and Graphical Statistics. 3.1, 35-56. Jones, M.C. and H.W. Lotwick. (1984) `Remark AS R50: A Remark on Algorithm AS 176. Kernal Density Estimation Using the Fast Fourier Transform`. Journal of the Royal Statistical Society. Series C. 33.1, 120-2. Silverman, B.W. (1982) `Algorithm AS 176. Kernel density estimation using the Fast Fourier Transform. Journal of the Royal Statistical Society. Series C. 31.2, 93-9. """ X = np.asarray(X) X = X[np.logical_and(X > clip[0], X < clip[1])] # won't work for two columns. # will affect underlying data? try: bw = float(bw) except: bw = bandwidths.select_bandwidth( X, bw, kernel) # will cross-val fit this pattern? bw *= adjust nobs = float(len(X)) # after trim # 1 Make grid and discretize the data if gridsize == None: gridsize = np.max((nobs, 512.)) gridsize = 2**np.ceil(np.log2(gridsize)) # round to next power of 2 a = np.min(X) - cut * bw b = np.max(X) + cut * bw grid, delta = np.linspace(a, b, gridsize, retstep=True) RANGE = b - a #TODO: Fix this? # This is the Silverman binning function, but I believe it's buggy (SS) # weighting according to Silverman # count = counts(X,grid) # binned = np.zeros_like(grid) #xi_{k} in Silverman # j = 0 # for k in range(int(gridsize-1)): # if count[k]>0: # there are points of X in the grid here # Xingrid = X[j:j+count[k]] # get all these points # # get weights at grid[k],grid[k+1] # binned[k] += np.sum(grid[k+1]-Xingrid) # binned[k+1] += np.sum(Xingrid-grid[k]) # j += count[k] # binned /= (nobs)*delta**2 # normalize binned to sum to 1/delta #NOTE: THE ABOVE IS WRONG, JUST TRY WITH LINEAR BINNING binned = linbin(X, a, b, gridsize) / (delta * nobs) # step 2 compute FFT of the weights, using Munro (1976) FFT convention y = forrt(binned) # step 3 and 4 for optimal bw compute zstar and the density estimate f # don't have to redo the above if just changing bw, ie., for cross val #NOTE: silverman_transform is the closed form solution of the FFT of the #gaussian kernel. Not yet sure how to generalize it. zstar = silverman_transform(bw, gridsize, RANGE) * y # 3.49 in Silverman # 3.50 w Gaussian kernel f = revrt(zstar) if retgrid: return f, grid, bw else: return f, bw
def kdensity(X, kernel="gauss", bw="scott", weights=None, gridsize=None, adjust=1, clip=(-np.inf,np.inf), cut=3, retgrid=True): """ Rosenblatz-Parzen univariate kernel desnity estimator Parameters ---------- X : array-like The variable for which the density estimate is desired. kernel : str The Kernel to be used. Choices are - "biw" for biweight - "cos" for cosine - "epa" for Epanechnikov - "gauss" for Gaussian. - "tri" for triangular - "triw" for triweight - "uni" for uniform bw : str, float "scott" - 1.059 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) "silverman" - .9 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) If a float is given, it is the bandwidth. weights : array or None Optional weights. If the X value is clipped, then this weight is also dropped. gridsize : int If gridsize is None, max(len(X), 50) is used. adjust : float An adjustment factor for the bw. Bandwidth becomes bw * adjust. clip : tuple Observations in X that are outside of the range given by clip are dropped. The number of observations in X is then shortened. cut : float Defines the length of the grid past the lowest and highest values of X so that the kernel goes to zero. The end points are -/+ cut*bw*{min(X) or max(X)} retgrid : bool Whether or not to return the grid over which the density is estimated. Returns ------- density : array The densities estimated at the grid points. grid : array, optional The grid points at which the density is estimated. Notes ----- Creates an intermediate (`gridsize` x `nobs`) array. Use FFT for a more computationally efficient version. """ X = np.asarray(X) if X.ndim == 1: X = X[:,None] clip_x = np.logical_and(X>clip[0], X<clip[1]) X = X[clip_x] nobs = float(len(X)) # after trim if gridsize == None: gridsize = max(nobs,50) # don't need to resize if no FFT # handle weights if weights is None: weights = np.ones(nobs) q = nobs else: if len(weights) != len(clip_x): msg = "The length of the weights must be the same as the given X." raise ValueError(msg) weights = weights[clip_x.squeeze()] q = weights.sum() # if bw is None, select optimal bandwidth for kernel try: bw = float(bw) except: bw = bandwidths.select_bandwidth(X, bw, kernel) bw *= adjust a = np.min(X,axis=0) - cut*bw b = np.max(X,axis=0) + cut*bw grid = np.linspace(a, b, gridsize) k = (X.T - grid[:,None])/bw # uses broadcasting to make a gridsize x nobs # instantiate kernel class kern = kernel_switch[kernel](h=bw) # truncate to domain if kern.domain is not None: # won't work for piecewise kernels like parzen z_lo, z_high = kern.domain domain_mask = (k < z_lo) | (k > z_high) k = kern(k) # estimate density k[domain_mask] = 0 else: k = kern(k) # estimate density k[k<0] = 0 # get rid of any negative values, do we need this? dens = np.dot(k,weights)/(q*bw) if retgrid: return dens, grid, bw else: return dens, bw
def kdensity(X, kernel="gauss", bw="scott", weights=None, gridsize=None, adjust=1, clip=(-np.inf, np.inf), cut=3, retgrid=True): """ Rosenblatz-Parzen univariate kernel desnity estimator Parameters ---------- X : array-like The variable for which the density estimate is desired. kernel : str The Kernel to be used. Choices are - "biw" for biweight - "cos" for cosine - "epa" for Epanechnikov - "gauss" for Gaussian. - "tri" for triangular - "triw" for triweight - "uni" for uniform bw : str, float "scott" - 1.059 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) "silverman" - .9 * A * nobs ** (-1/5.), where A is min(std(X),IQR/1.34) If a float is given, it is the bandwidth. weights : array or None Optional weights. If the X value is clipped, then this weight is also dropped. gridsize : int If gridsize is None, max(len(X), 50) is used. adjust : float An adjustment factor for the bw. Bandwidth becomes bw * adjust. clip : tuple Observations in X that are outside of the range given by clip are dropped. The number of observations in X is then shortened. cut : float Defines the length of the grid past the lowest and highest values of X so that the kernel goes to zero. The end points are -/+ cut*bw*{min(X) or max(X)} retgrid : bool Whether or not to return the grid over which the density is estimated. Returns ------- density : array The densities estimated at the grid points. grid : array, optional The grid points at which the density is estimated. Notes ----- Creates an intermediate (`gridsize` x `nobs`) array. Use FFT for a more computationally efficient version. """ X = np.asarray(X) if X.ndim == 1: X = X[:, None] clip_x = np.logical_and(X > clip[0], X < clip[1]) X = X[clip_x] nobs = float(len(X)) # after trim if gridsize == None: gridsize = max(nobs, 50) # don't need to resize if no FFT # handle weights if weights is None: weights = np.ones(nobs) q = nobs else: if len(weights) != len(clip_x): msg = "The length of the weights must be the same as the given X." raise ValueError(msg) weights = weights[clip_x.squeeze()] q = weights.sum() # if bw is None, select optimal bandwidth for kernel try: bw = float(bw) except: bw = bandwidths.select_bandwidth(X, bw, kernel) bw *= adjust a = np.min(X, axis=0) - cut * bw b = np.max(X, axis=0) + cut * bw grid = np.linspace(a, b, gridsize) k = (X.T - grid[:, None]) / bw # uses broadcasting to make a gridsize x nobs # instantiate kernel class kern = kernel_switch[kernel](h=bw) # truncate to domain if kern.domain is not None: # won't work for piecewise kernels like parzen z_lo, z_high = kern.domain domain_mask = (k < z_lo) | (k > z_high) k = kern(k) # estimate density k[domain_mask] = 0 else: k = kern(k) # estimate density k[k < 0] = 0 # get rid of any negative values, do we need this? dens = np.dot(k, weights) / (q * bw) if retgrid: return dens, grid, bw else: return dens, bw