scieee AI-readable full text Open interactive document viewer

Statistical Computing in Functional Data Analysis: The R Package fda.usc

Febrero Bande, Manuel; Oviedo de la Fuente, Manuel

Abstract

This paper is devoted to the R package fda.usc which includes some utilities for functional data analysis. This package carries out exploratory and descriptive analysis of functional data analyzing its most important features such as depth measurements or functional outliers detection, among others. The R package fda.usc also includes functions to compute functional regression models, with a scalar response and a functional explanatory data via non-parametric functional regression, basis representation or functional principal components analysis. There are natural extensions such as functional linear models and semi-functional partial linear models, which allow non-functional covariates and factors and make predictions. The functions of this package complement and incorporate the two main references of functional data analysis: The R package fda and the functions implemented by Ferraty and Vieu (2006)

Full text

JSS Journal of Statistical Software October 2012, Volume 51, Issue 4. http://www.jstatsoft.org/ Statistical Computing in Functional Data Analysis: The RPackage fda.usc Manuel Febrero-Bande Universidad de Santiago de Compostela Manuel Oviedo de la Fuente Universidad de Santiago de Compostela Abstract This paper is devoted to the Rpackage fda.usc which includes some utilities for functional data analysis. This package carries out exploratory and descriptive analysis of functional data analyzing its most important features such as depth measurements or functional outliers detection, among others. The Rpackage fda.usc also includes functions to compute functional regression models, with a scalar response and a functional explanatory data via non-parametric functional regression, basis representation or functional principal components analysis. There are natural extensions such as functional linear models and semi-functional partial linear models, which allow non-functional covariates and factors and make predictions. The functions of this package complement and incorporate the two main references of functional data analysis: The Rpackage fda and the functions implemented by Ferraty and Vieu (2006). Keywords: functional data regression, representation of functional data, non-parametric kernel estimation, depth measures, outlier. 1. Introduction The technological progress has led to the development of new, quick and accurate measurement procedures. As a consequence, further possibilities for obtaining experimental data are now available and some classical paradigms must be revised. For example, it is now possible (and even frequent) to find problems where the number of data points is greater than the number of variables. In many areas it is common to work with large databases, which often increase these observations of a random variable taken over a continuous interval (or in increasingly larger discretizations of a continuous interval). For example, in fields such as spectroscopy, the measurement result is a curve that, at least, 2fda.usc: Functional Data Analysis in R has been evaluated in 100 points. This type of data, which we call functional data arise naturally in many disciplines. In economics, one could consider curves intra-day stock quotes. In environmental studies, one could find continuous measurements of atmospheric monitoring networks. The importance of functional data in image recognition or spatio-temporal information is also well-known. Undoubtedly, package fda (Ramsay, Wickham, Graves, and Hooker 2012) is a basic reference to work in Rprogramming environment (RDevelopment Core Team 2012) with functional data. The books by Ramsay and Silverman (2005) and Ramsay and Silverman (2002) are well-known references in this field. In both cases all the techniques included are restricted to the space of L2functions (the Hilbert space of all square integrable functions over a certain interval). The book by Ferraty and Vieu (2006) is another important reference incorporating non-parametric approaches as well as the use of other theoretical tools such as semi-norms and small ball probabilities that allow us to deal with normed or metric spaces. These authors are part of the French group STAPH maintaining the page http://www.lsp.ups-tlse.fr/staph where Rsoftware can be downloaded. Other Rsoftware provides implementation of functional data analysis (FDA) in different areas. The package rainbow (Shang and Hyndman 2012) for functional data representation, the package ftsa (Hyndman and Shang 2012) for functional time series analysis, the package refund (Crainiceanu, Reiss, Goldsmith, Huang, Huo, and Scheipl 2012) for functional penalized regression, the package fpca (Peng and Paul 2011) implements the restricted maximum likelihood estimation for functional principal components analysis (FPCA), the package MFDF (Dou 2009) for modeling functional data in finance via generalized linear models (GLM), the package fdaMixed (Markussen 2011), for FDA in a mixed model framework and the package geofd (Giraldo, Delicado, and Mateu 2010) for spatial prediction for function value data. In MATLAB PACE package (see http://anson.ucdavis.edu/~ntyang/PACE/) provides implementation of various methods using FPCA as generalized functional linear models (GFLM) for sparsely sampled functional data, this package is also in R(Liu 2011). Finally, from a Bayesian perspective, Crainiceanu and Goldsmith (2010) have developed tools for GFLM using WinBUGS. The aim of the package fda.usc is to provide a broader, flexible tool for the analysis of functional data. Therefore, we propose an integration of the work on non-parametric functional methods implemented by Ferraty and Vieu (2006) with those from the group of the University of Santiago de Compostela (USC), thus complementing and extending some of the functions of package fda. The fda.usc package is available from the Comprehensive RArchive Network at http://CRAN.R-project.org/package=fda.usc and it has the greedy objective of being an integrate framework for all the functional data methods available. In Section 2.1 we introduce a new Rclass for functional data: “fdata”. Section 2.2 describes the functional representation of an object of class “fdata” by basis representation or kernel smoothing. Section 2.3 is focused in normed and semi-normed functional spaces and in how the metrics and semimetrics can be used as measures of proximity between functional data. Section 2.4 is concerned with the concept of statistical depth for functional data see Cuevas, Febrero-Bande, and Fraiman (2007). These depth measures are useful to define location and dispersion measures, for classification and for outlier detection (Febrero-Bande, Galeano, and Gonz´alez-Manteiga 2008) (Section 2.6). Section 3is devoted to functional regression models with scalar response from different perspectives: Parametric, using basis representation (Section 3.1,3.2 and 3.3), non-parametric, using kernel smoothing (Section 3.4) and semi- Journal of Statistical Software 3 parametric which combines both (Section 3.5). The Section 3.6 summarizes the functional regression models using a classical example to show the capabilities of the package fda.usc. Finally, Section 4discusses the most important features of the package. 2. Functional data: Definition and descriptive analysis After a brief introduction of the state of the art in functional data, we describe the most important features, procedures and utilities of the new package. This article is not intended to enter into many methodological details because most of the functions of the package are adaptations of original functions studied in previous publications. 2.1. Functional data definition: The new Rclass “fdata” A functional variable Xis just a random variable taking values in a functional space E. Thus, a functional data set is just a sample {X1,...,Xn}(also denoted X1(t), . . . , Xn(t) when convenient) drawn from a functional variable X. Usually, Eis assumed to be a normed or seminormed metric space. If Eis a Hilbert space, functional data can be represented using a basis. This is the approach of the fda package for its methodological developments and it is also used by refund,geofd or MFDF packages, among others. In practice, this representation projects an infinite dimensional space into a finite one and has the drawback of the approximation of the original data. However, the functional space Emay not be Hilbertian and in this case, a more flexible representation of functional data is needed. For this reason, this package introduces the new class“fdata”. This new class uses only the values evaluated on a grid of discretization points {t1, . . . , tm}that can be observed in a non-equispaced way. The drawback now is that every calculation (distance, norms,...) must be made through numerical approximations and the design or the density of this grid could affect the accuracy of the calculations. If functional data is sparsely sampled or there are many missing data points, probably the representation in a basis is mandatory and some other alternatives, as for example PACE package, should be considered. The fda.usc package defines an object called fdata as a list of the following components:  data: Typically a matrix of (n, m) dimension which contains a set of ncurves discretized in mpoints or argvals.  argvals: Locations of the discretization points, by default: {t1= 1, . . . , tm=m}.  rangeval: Range of discretization points, by default: range(argvals).  names: Optional list with three components: main, an overall title, xlab, a title for the x axis and ylab, a title for the y axis. All the methods in the package can work with the new class “fdata”. Some basic operations to handle this new class are introduced. For example, generic methods for the math group abs,sqrt,round,exp,log,cumsum; for the OPS group “+”, “-”, “*”, “/”, “==”, “<”, ‘>”, “<=”, ‘>=”; the for summary group all,any,sum,min,max; and other operations is.fdata(), c(),dim(),ncol(),nrow(),plot(),inprod.fdata() and norm.fdata(). To calculate the derivative of functional data the fdata.deriv() function has been implemented, which computes the derivative by different methods, some purely numerical and others based on a 4fda.usc: Functional Data Analysis in R Figure 1: Spectrometric curves (left panel): curves with Fat <20% (red lines) and curves with Fat ≥20% (blue lines). Corresponding spectrometic curves after first order differencing (right panel). basis representation. The choice of the right method depends on the nature of the data and on the grid of discretization. The function fdata() converts a data object of class: “fd”, “fds”, “fts”, “sfts” or other formats (“vector”, “matrix”, “data.frame”) to an object of class “fdata”. We have included in the“fdata”format some popular datasets of functional data: tecator,phoneme,poblenou and aemet. As an illustration we applied some of above methods to the tecator dataset (data("tecator")) that has two components. The first component, tecator$absorp.fdata, includes the curves of absorbance for the analysis of pieces of meat stored in the format of class “fdata”. Each curve consists of a m=100-channel absorbance spectrum measured along the discretized points: argvals ={t1= 850, . . . , tm= 1050}. The second component, tecator$y, is a dataframe including Fat,Water and Protein contents of each spectrometric curve obtained by an analytical chemical processing. The tecator dataset presents interesting features and it is a well known example in functional data analysis (available at http:// lib.stat.cmu.edu/datasets/tecator). The following code displays the absorbance curves colored by the fat content, see Figure 1. R> library("fda.usc") R> data("tecator") R> names(tecator) [1] "absorp.fdata" "y" Journal of Statistical Software 5 R> absorp <- tecator$absorp.fdata R> Fat20 <- ifelse(tecator$y$Fat < 20, 0, 1) * 2 + 2 R> plot(tecator$absorp.fdata, col = Fat20) R> absorp.d1 <- fdata.deriv(absorp, nderiv = 1) R> plot(absorp.d1, col = Fat20) The representation of a functional dataset should be consistent with the physical interpretation of the phenomenon being described and so it is important to choose the space where the data must be considered. For example, in left panel of Figure 1, the spectrometric curves are plotted showing with different colors two levels of fat content. This representation which implicitly assumes a L2space, is not related with the information of fat content. In other words, the vertical shift of these curves has no special relation with the fat content. So, if we are interested in the relationship between the spectrometric curve and the fat content, probably another choice of functional space would be more advisable as shown, for example, in the right panel of Figure 1with the first derivative of the spectrometric curves. 2.2. Smoothing If we assume that our functional data Y(t) is observed through the model: Y(ti) = X(ti)+(ti) where the residuals (t) are independent from X(t), we can get back the original signal X(t) using a linear smoother, ˆx= n X i=1 sijyior ˆx=Sy where sij is the weight that the point tjgives to the point tiand yi=Y(ti). In the package two procedures have been implemented for this purpose. The first one is the representation in aL2basis (or penalized basis) and the second one is based on the smoothing kernel methods. Basis representation A curve can be represented by a basis when the data is assumed to belong to L2space. A basis is a set of known functions {φk}k∈Nthat any function could be arbitrarily approximated by a linear combination of a sufficiently large number knof these functions, see Ramsay and Silverman (2005, p. 43 and 44). The procedure recovers the function X(t) by using a fixed truncated basis expansion in terms of knknown basis elements, X(t) = X k∈N ckφk(t)≈ kn X k=1 ckφk(t) = c>Φ(t) (1) The projection (or smoothing) matrix is given by: S= Φ(Φ>Φ)−1Φ>, with degrees of freedom of the fit df = tr(Sν) = kn. If smoothing penalization is required, a parameter λwill also be provided and in this case the projection matrix Sis: S= Φ(Φ>Φ + λR)−1Φ>, where Ris the penalization matrix. Typically Rpenalizes the integral of the square of the derivative of order 2. 6fda.usc: Functional Data Analysis in R There are several different types of basis (Fourier, B-spline, Exponential, power, polynomial, . . . ) that can be created using the function create.fdata.basis() or directly through the create.basis-name.basis from the fda package. This package also includes the basis functions based on the data: create.pc.basis() and create.pls.basis() that provides a functional principal component and partial least square basis, respectively. The choice of the basis should be based on the objective of the analysis and on the data. For example, it is common to use the Fourier basis for periodic data, and B-spline basis for non-recurrent data. Also, the function fdata2fd() converts an object of class “fdata” into an object of class “fd” using the basis representation shown in (1). R> class(absorp.fd <- fdata2fd(absorp, type.basis= "fourier", nbasis= 15)) [1] "fd" R> class(absorp.fdata <- fdata(absorp.fd)) [1] "fdata" Kernel smoothing The non-parametric methodology and in particular, the kernel smoothing method, can also be used to represent functional data. Now, the non-parametric smoothing of functional data is given by the smoothing matrix S= (sij). For example, for the Nadaraya-Watson estimator (function S.NW()): sj(ti) = Kti−tj h/Pm k=1 Kti−tk hwhere K(·) is the kernel function. Other possibilities for S are the knearest neighbors estimator (function S.KNN()) or the local linear regression estimator (function S.LLR()), see Wasserman (2006), Ferraty and Vieu (2006) for futher details. Many different types of kernels are considered in the package: Gaussian, Epanechnikov, triweight, uniform, cosine or any user-defined. Validation criterion The choice of the smoothing parameter is crucial and, in principle, there is no universal rule that would enable an optimal choice. Among the different selection criterion to select the parameter ν, we have implemented two: Cross-validation (CV) and generalized crossvalidation (GCV). Cross-validation : CV (ν) = 1 n n X i=1 yi−ˆyν −i2wi(2) where ˆyν i(−i)indicates the estimator based on leaving out the ipair (ti, yi) and wiis the weight at point ti. This criterion is implemented by the function CV.S(). Generalized cross-validation : GCV (ν) = 1 n n X i=1 yi−ˆyν i2wiΞ(ν) (3) where Ξ(ν) denotes the type of penalizing function. Generalized cross-validation criterion is implemented in GCV.S() function with the following types of penalized functions (see H¨ ardle 1990, for futher details): Journal of Statistical Software 7  Generalized cross-validation (GCV): Ξ(ν) = (1 −tr(Sν)n−1)−2.  Akaike’s information criterion (AIC): Ξ(ν) = exp(2tr(Sν)n−1).  Finite prediction error (FPE): Ξ(ν) = (1 + tr(Sν)n−1)/(1 −tr(Sν)n−1).  Shibata’s model selector (Shibata): Ξ(ν) = (1 + 2tr(Sν)n−1).  Rice’s bandwidth selector (Rice): Ξ(ν) = (1 −2tr(Sν)n−1)−1. Smoothing FDA with fda.usc package Let us now consider, for illustration purposes, the Phoneme dataset data("phoneme")1see, e.g., Ferraty and Vieu (2006). The phoneme$classlearn object contains 250 speech frames with class membership: “sh” (1), “iy” (2), “dcl” (3), “aa” (4) and “ao” (5). From each speech frame, a log-periodogram of length 150 has been stored in phoneme$learn which is used as learning sample. The goal is to predict the class membership phoneme$classtest using the test sample phoneme$test. The purpose of the function min.basis() is to represent the functional data in terms of a (truncated) expansion with respect to a given basis of functions in the corresponding space. Such expansions depend on a parameter ν= (kn, λ), where knis the number of basis elements used in the truncated expansion and λis the penalization parameter. In the following example (see below Rcode), phoneme$learn is smoothed using min.basis() function. R> data("phoneme") R> learn <- phoneme$learn R> l <- c(0, 2^seq(-2, 9, length.out = 30)) R> nb <- seq(7, 31, by = 2) R> out0 <- min.basis(learn, lambda = l, numbasis = nb) The minimum GCV (GCV.OPT=2.3815) is achieved with the number of basis (numbasis.opt=27) and lambda value (lambda.opt=81.27995) In the left panel of Figure 2, the GCV criterion is drawn in function of the number of B- spline basis elements ν1=nbasis and the penalizing parameter ν2=λusing min.basis() function and the smoothed functional data ˆx(t) (in out0$fdata.est object) can be used as the signal we have tried to recover. Figure 3shows the 11th curve of speech frame x11 (phoneme$learn[11]) and the smooth representation of the curve ˆx11 (out0$fdata.est[11]). The min.np() function returns the “optimal” value (in out1$h.opt) of the smoothing parameter ν=hthat best represents the functional data for a range of values of bandwidth h using the validation criterion (2) and (3) shown above. As an illustration, in the right panel of Figure 2, the GCV criterion is drawn in function of the bandwidth husing the function min.np() and Figure 3shows smooth representation of 11th curve of phoneme$learn by Nadaraya-Watson (S.NW()), local linear regression (S.LLR()) method and Knearest neighbors (S.KNN()) method. 1This dataset includes the changes introduced in the file http://www.math.univ-toulouse.fr/staph/ npfda/npfda-phondiscRS.txt. 8fda.usc: Functional Data Analysis in R Figure 2: GCV criterion as a function of the number of B-spline basis elements and the penalizing parameter λ(left panel). GCV criterion as a function of bandwidth parameter (right panel): Normal kernel and local linear smoothing matrix (blue line); Normal kernel and Nadaraya-Watson smoothing matrix (green line) and uniform kernel and Knearest neighbors smoothing matrix (red line). Figure 3: Eleventh phoneme curve: Observed (grey dashed line), smoothed by 27 B-spline basis elements and λ= 81.28 (black line), smoothed by normal kernel and Nadaraya-Watson smoothing matrix with bandwidth h= 3.28 (green line), smoothed by normal kernel and local linear smoothing matrix with bandwidth h= 7.85 (blue line) and smoothed by uniform kernel and Knearest neighbors smoothing matrix with bandwidth h= 7 (red line). Journal of Statistical Software 9 R> out1 <- min.np(learn, type.S = S.NW, par.CV = list(criteria = "GCV")) The minimum GCV (GCV.OPT=2.4119) is achieved with the h value (h.opt=3.2765) R> out2 <- min.np(learn, type.S = S.LLR, par.CV = list(criteria = "GCV")) The minimum GCV (GCV.OPT=2.5363) is achieved with the h value (h.opt=7.9482) R> out3 <- min.np(learn, type.S = S.KNN, h = 3:25, Ker = Ker.unif) The minimum GCV (GCV.OPT=2.3746) is achieved with the h value (h.opt=7) 2.3. Measuring distances Sometimes, it is difficult to find the best plot to summarize a particular functional dataset because the shape of the graphics depends strongly on the chosen proximity measure. As shown in Figure 1, the plot of X(t) against tis not necessarily the most informative and perhaps, considering another distance between curves we can obtain better results. This package collects several metric and semi-metric functions which allow us to extract as much information possible from the functional variable. The most general spaces for functional data are the complete metric spaces where only the notion of distance between elements of the space is given. If the metric d(·,·) is associated with a norm (so that d(X(t), Y (t)) = kX(t)−Y(t)k) we have a normed space (or a Banach space). In some important cases the norm k.kis associated with an inner product h., .iin the sense that kXk=hX, Xi1/2. A complete normed space (Banach space) whose norm derives from an inner product is called a Hilbert space. The best known example is the space L2[a, b] of real square-integrable functions defined on [a, b] with hf, gi=Rb afg. Utilities for computing distances, norms and inner products are included in the package. If we focused on Lpspaces (the set of functions whose absolute value raised to the p-th power has finite integral), the function metric.lp() uses Simpson’s rule to compute distances between elements: kf(t)−g(t)kp=1 Rb aw(t)dt Rb a|f(t)−g(t)|pw(t)dt1/p where ware the weight and the observed points on each curve tare equally spaced (by default) or not. norm.fdata() computes the norm and, specifically for L2,inprod.fdata() calculates the inner product between elements of the space. In the next example, the distances between some training sample curves of phoneme data (phoneme$learn) are calculated by the metric.lp() function. Figure 4shows the dendrogram for a selection of 11 curves of class (3) (corresponding to the index from 110 to 120 curves) and 11 curves of class (5) (from 220 to 230). This example can be understood as a classification problem in which the goal is to classify the curves in 2 classes. R> mdist <- metric.lp(learn) 16 fda.usc: Functional Data Analysis in R Figure 8: Summary plots for fitted object (res.basis1) from a functional linear model with basis representation (fregre.basis()). fregre.basis.cv() uses validation criterion defined in Section 2.2 by argument type.CV to estimate the number of basis elements and/or the penalized parameter (λ) that best predicts the response. Going on with the example, the next code illustrates how to estimate the fat contents (y = Fat) using a training sample of 1st derivative absorbance curves X.d1. R> rangett <- absorp$rangeval R> basis1 <- create.fourier.basis(rangeval = rangett, nbasis = 5) R> res.basis1 <- fregre.basis(X.d1, y, basis.x = basis1) The fitted object (res.basis1) contains useful information as the smoothing parameter (ν), the degrees of freedom (df ), the residual variance (S2 R): S2 R=Pn i=1 (yi−ˆyi)2/(n−df) (an unbiased estimator of σ2), the coefficient of determination (R2) or the hat matrix (H). This information is used in summary.fregre.fd() and print.fregre.fd() to show summaries of the functional regression fitted model, see Figure 8. Journal of Statistical Software 17 3.2. Functional linear model with functional PC basis: fregre.pc() Similarly, Cardot, Ferraty, and Sarda (1999) used a {νk}∞ k=1 orthonormal basis of functional principal components to represent the functional data as Xi(t) = P∞ k=1 γikνkand the functional parameter as β(t) = P∞ k=1 βkνk, where γik =hXi(t), νkiand βk=hβ, νki. Now, the estimation of β(t) can be made by a few principal components (PCs) under the assumption that βk= 0, for k > knand the integral can be approximated by: ˆy=DX, ˆ βE≈ kn X k=1 γik ˆ βk(6) where, ˆ β(1:kn)=γ> .1y nλ1,...,γ> .kny nλknand γ(1:kn)is the (n,kn) matrix with knprincipal components estimation of βscores and λithe eigenvalues of the PC. The model of Equation 6is expressed as: ˆy=Hywhere H=γ.1γ> .1y nλ1,...,γ.knγ> .kny nλknwith degrees of freedom: df = tr(H) = kn. We have implemented the functional principal regression in the function fregre.pc(). The call for tecator example is shown below: R> res.pc1 <- fregre.pc(X.d1, y, l = 1:6) For the fitted object of fregre.pc() function, the function summary.fregre.fd() also shows:  Variability of explicative variables explained by principal components.  Variability for each principal component. How to select kn:fregre.pc.cv() The novelty of the procedure used in fregre.pc.cv() is that the algorithm selects the principal components that best estimated the response. The selection is done by cross-validation (CV) or model selection criteria (MSC).  Predictive cross-validation: PCV (kn) = 1 nPn i=1 yi−DXi,ˆ β(−i,kn)E2,criteria = "CV".  Model selection criteria: MSC (kn) = log 1 nPn i=1 yi−DXi,ˆ β(i,kn)E2+pnkn nwith pn=log(n) nfor criteria = "SIC" (by default), pn=log(n) n−kn−2for criteria = "SICc", pn= 2 for criteria = "AIC", pn=2n n−kn−2for criteria = "AICc", where criteria is an argument of the function fregre.pc.cv() that controls the type of validation used in the selection of the smoothing parameter kn. In the following example the regression model is fitted using the best selection of first 7 functional principal components (FPCs). The minimum MSC (MSC = 2.128167) is achieved with the FPC 1, 2, 7, 3 and 6 using the SIC criterion. 18 fda.usc: Functional Data Analysis in R R> res.pc2 <- fregre.pc.cv(X.d2, y, kmax = 7) R> res.pc2$pc.opt PC1 PC2 PC7 PC3 PC6 12736 R> res.pc2$MSC PC(1) PC(2) PC(3) PC(4) PC(5) PC(6) PC(7) rn=0 2.852951 2.258292 2.144443 2.13227 2.128167 2.159107 2.190052 Functional linear model with functional PLS basis: fregre.pls() In the previous section, the dimension reduction by FPCs is a good solution for the estimation of the functional linear model. Another good alternative is the use of the criterion that maximizes the covariance between X(t) and the scalar response Yvia the partial least squares (PLS) components. Let {˜νk}∞ k=1 the functional PLS components (Preda and Saporta 2005) and as before Xi(t) = P∞ k=1 ˜γik ˜νkand β(t) = P∞ k=1 ˜ βk˜νk. The functional linear model is estimated by: ˆy=DX, ˆ βE≈ kn X k=1 ˜γik ˜ βk(7) We have implemented the FPLS regression in the function fregre.pls() where the PLS factors have been calculated using an alternative formulation of the NIPALS algorithm proposed by Kr¨ amer and Sugiyama (2011). The call for tecator example and the print of the fitted object are shown below: R> fregre.pls(X.d1, y, l = 1:5) -Call: fregre.pls(fdataobj = X.d1, y = y, l = 1:5) -Coefficients: (Intercept) PLS1 PLS2 PLS3 PLS4 PLS5 17.39 491.92 142.44 230.95 134.00 186.78 -R squared: 0.9508922 -Residual variance: 7.927896 Functional influence measures: influence.fdata() This section focuses on how to identify influential observations in the FLM discussed in the previous sections. Febrero-Bande, Galeano, and Gonz´alez-Manteiga (2010) studied three statistics for measuring the influence: Cook prediction distance (CPi), Cook estimation distance (CEi) and Pe˜na’s distance (Pi), respectively. Journal of Statistical Software 19 Figure 9: Influence measures for tecator dataset calculated from fitted model (res.basis0): Matrix of scatter plots for Cook prediction distance (CPi), Cook estimation distance (CEi) and Pe˜na’s distance (Pi). 1. The functional Cook’s measure for prediction (CPi) detects observations whose deletion may entail important changes in the prediction of the rest of the data. It is defined as CPi=(ˆy−ˆy−i)>(ˆy−ˆy−i) S2 R where ˆy−iis the prediction of the response yexcluding the i-th observation (Xi, yi). 2. The functional Cook’s measure for estimation (CEi) detects observations whose deletion may entail important changes in the estimation. CEi=   ˆ β−ˆ β−i   2 S2 R nPkn k=1 1 λk where ˆ β−iis the estimator of the parameter βexcluding the i-th observation (Xi, yi) in the process. 3. The functional Pe˜na’s measure for prediction (Pi) detects observations whose prediction is most affected by the deletion of other data. Pi=(ˆyi−ˆy(−1,i), ..., ˆyi−ˆy(−n,i))>(ˆyi−ˆy(−1,i), ..., ˆyi−ˆy(−n,i)) S2 RHii where ˆy(−h,i)is the i-th component of the prediction vector ˆy(−h)for h= 1, ..., n. 20 fda.usc: Functional Data Analysis in R Once estimated the functional regression model with scalar response (by fregre.basis(), fregre.pc() or fregre.pls()), the influence.fdata() function is used to obtain the influence measures, see Figure 9. Febrero-Bande et al. (2010) propose to approximate quantiles of the above statistics by means of a procedure which uses smoothed bootstrap samples of the set of observations of the above statistics. This package includes the above procedure in influence.quan() function. When the goal is to make inferences about the functional parameter and not on influence measures, one advantage derived from this procedure is that the calculation takes into account the mue.boot curves of the functional parameter β(t) in the functional Cook’s measure for estimation. However, this procedure has a very high computational cost. In order to reduce substantially the computational time we have created the fregre.bootstrap() function which is explained below. Bootstrap for functional linear model We can study the variability of functional beta parameter β, which is estimated by the previously functional regression models (fregre.basis(),fregre.pc() and fregre.pls()), using the confidence ball (CB) defined as follows, CB(ˆ βν) = nβ∈ L2:  β−ˆ βν  < Dαo(8) where Dαsuch that Pr β∈CB(ˆ βν)= 1 −α. To do this, we have followed the smoothed bootstrap procedure proposed by Febrero-Bande et al. (2010). Given nscalar responses Y and nfunctional data X. 1. Fit the functional linear model in Equation 4and compute the residuals e. 2. Obtain Bstandard bootstrap samples of size nof the residuals: eb 1, . . . , eb n, for b= 1, . . . , B. Similarly, obtain Bstandard bootstrap samples of the functional data: Xb 1, . . . , Xb n. 3. Smooth the two previous samples as follows: (i) Obtain ˜ Xb i=Xb i+Zb isuch Zb iis a Gaussian process with zero mean and the covariance operator γXΓX, where γXis a smoothed bootstrap parameter. (ii) Obtain ˜eb i=eb i+Zb isuch zb iis normally distributed with mean 0 and variance γeS2 R, where γeis a smoothed bootstrap parameter. 4. Obtain: ˜yb i=D˜ Xb i,˜ βνE+ ˜eb ifor b= 1, . . . , B,i= 1, . . . , n, where ˜ βνis the estimate of β obtained in step 1. 5. Fit the model 4to the smoothed bootstrap ˜ Yband ˜ Xb. 6. Dαin Equation 8is estimated by the (1 −α) quantile ˆ Dαof    ˆ βν−ˆ βi ν   B i=1. 7. Plot the bootstrap replicates nˆ βi νoB i=1 such that    ˆ βν−ˆ βi ν  <ˆ Dα. In Figure 10, the bootstrap confidence ball is plotted for the three fitted models (res.basis1, res.pc1 and res.pls1), with nˆ βi νo1000 i=1 and (1 −α)=0.999. Those replicates belonging to Journal of Statistical Software 21 Figure 10: Estimated regression function ˆ βνjoint with a 99.9% bootstrap confidence ball by: fregre.basis() (left), fregre.pc() (center) and fregre.pls() (right). Red curve correspond to that resample not in the bootstrap confidence ball. the confidence ball are drawn in gray whereas the curve falling outside is drawn in red. The parameter ˆ βν(blue line) is clearly significant (different from 0) showing the maximum difference in the first half of wavelength interval. In the function fregre.bootstrap(), the smoothed bootstrap parameters γXand γeare the arguments smoX and smo, respectively. In step 4, the argument kmax.fix can be selected by an appropriated cutoff νin each biteration or fixed its value in the step 1. In the example, we have used a small resample nb = 1000 and we have fixed the parameter kmax.fix (5 Fourier basis, 6 FPC and 5 FPLS) to have a reasonable computing time. Still, the calculation procedure is computationally high demanding. R> fregre.bootstrap(res.basis1, nb = 1000, kmax.fix = TRUE, alpha = 0.999) R> fregre.bootstrap(res.pc1, nb = 1000, kmax.fix = TRUE, alpha = 0.999) R> fregre.bootstrap(res.pls1, nb = 1000, kmax.fix = TRUE, alpha = 0.999) 3.3. Functional linear model with functional and non-functional covariate: fregre.pls() This section is presented as an extension of the previous linear regression models. Now, the scalar response Yis estimated by more than one functional covariate Xj(t) and also more 22 fda.usc: Functional Data Analysis in R than one non-functional covariate Zj. The regression model is given by: yi=α+β1Z1 i+···+βpZp i+1 √T1ZT1 X1 i(t)β1(t)dt +···+1 pTqZTq Xq i(t)βq(t)dt +i(9) where Z=Z1,··· , Zpare the non-functional covariates and X(t) = X1(t1),··· , Xq(tq) are the functional ones. The functional linear model (9) is estimated by the expression: ˆy=˜ Xˆ b=˜ X(˜ X>˜ X)−1˜ X>y=Hy where ˜ X=Z1,··· , Zp,(C1)>ψ(t1)φ>(t1),··· ,(Cq)>ψ(tq)φ>(tq) The arguments are as follows:  formula: A symbolic description of the model to be fitted.  data: List containing the variables in the model. The first item in the data list is a “data.frame” called df with the response and non-functional explanatory covariates. Functional covariates (“fdata” or “fd” class) are introduced in the following items in the data list.  basis.x: List with a basis object for every functional covariate.  basis.b: List with a basis object for estimating the functional parameter β(t). For the tecator data example, the content of Fat is estimated from the second derivative of absorbances curves X.d2 and the content of Water by fregre.lm() function. R> ind <- 1:165 R> dataf <- as.data.frame(tecator$y[ind, ]) R> newdataf <- as.data.frame(tecator$y[-ind, ]) R> ldata <- list(df = dataf, X = X, X.d1 = X.d1, X.d2 = X.d2) R> f2 <- Fat ~ Water + X.d2 R> basis.x1 <- list(X.d2 = basis1) R> basis2 <- create.bspline.basis(rangeval = rangett, nbasis = 5) R> basis.b1 <- list(X.d2 = basis2) R> res.lm2 <- fregre.lm(f2, ldata, basis.x = basis.x1, basis.b = basis.b1) [1] "Non functional covariate: Water" [1] "Functional covariate: X.d2" 3.4. Non-parametric functional regression model: fregre.np() An alternative to model of Equation 4is the non-parametric functional regression studied by Ferraty and Vieu (2006). In this case, the regression model is written as yi=r(Xi(t)) + i,(10) Journal of Statistical Software 23 where the unknown smooth real function ris estimated using kernel estimation by means of ˆr(X) = Pn i=1 K(h−1d(X, Xi))yi Pn i=1 K(h−1d(X, Xi)) where K(·) is an kernel function, his the smoothing parameter and d(·,·) is a metric or a semi-metric. Now, the kernel is applied to a metric or semi-metrics that provides non-negative values, so it is common to use asymmetric kernels. This procedure is implemented in the fregre.np() function and some of its arguments are:  Ker: Type of asymmetric kernel function, by default asymmetric normal kernel.  metric: Type of metric or semi-metric, by default L2(metric.lp(...,lp = 2)).  type.S: Type of smoothing matrix S, by default Nadaraya Watson (S.NW()). Again, the function fregre.np.cv() is used to choose the smoothing parameter hby the validation criterion described in Section 2.2.  type.CV: Type of validation criterion, by default GCV criterion (GCV.S()). The code for the tecator example is: R> fregre.np(X.d1,y) -Call: fregre.np(fdataobj = X.d1, y = y) -Bandwidth (h): 0.006498587 -R squared: 0.9873025 -Residual variance: 3.036685 3.5. Semi-functional partially linear model: fregre.plm() An extension of the non-parametric functional regression models is the semi-functional partial linear model proposed in Aneiros-P´erez and Vieu (2006). This model uses a non-parametric kernel procedure as that described in Section 3.4. The output yis scalar. A functional covariate Xand a multivariate non-functional covariate Zare considered. y=r(X) + p X j=1 Zjβj+(11) The unknown smooth real function ris estimated by means of ˆrh(X) = n X i=1 wn,h(X, Xi)(Yi−Z> iˆ βh) where Whis the weight function: wn,h(X, Xi) = K(d(X,Xi)/h) Pn j=1 K(d(X,Xj)/h)with smoothing parameter h, an asymmetric kernel K(·) and a metric or semi-metric d(·,·). In fregre.plm() by default Whis a functional version of the Nadaraya-Watson-type weights (type.S = S.NW) with 24 fda.usc: Functional Data Analysis in R asymmetric normal kernel (Ker = AKer.norm) in L2(metric = metric.lp with p=2). The unknown parameters βjfor the multivariate non-functional covariates are estimated by means of ˆ βj= ( ˜ Z> h˜ Zh)−1˜ Z> h˜ Zhwhere ˜ Zh= (I−Wh)Zwith the smoothing parameter h. The errors are independent, with zero mean, finite variance σ2and E[|Z1, . . . , Zp, X(t)] = 0. Coming back to the example of Section 3.3, the fitted model for the case of a real variable Z = Water and the second derivative of the absorbance curves (X.d2) as functional covariate can be obtained by: R> res.plm2 <- fregre.plm( Fat ~ Water + X.d2, ldata) -Call: fregre.plm(formula = Fat ~ Water + X.d2, data = ldata) -Coefficients: Estimate Std. Error t value Pr(>|t|) Water -5.934e-01 6.463e-02 -9.181e+00 2.085e-13 -Bandwidth (h): 0.0003614096 -R squared: 0.9972631 -Residual variance: 0.6986455 3.6. Prediction methods for functional regression model fits Once the model is estimated we can obtain predictions by means of:  predict.fregre.fd() corresponds to the model fitted from fregre.basis(), fregre.pc(),fregre.pls() or fregre.np() functions.  predict.fregre.lm() corresponds to the model fitted from fregre.lm() function.  predict.fregre.plm() corresponds to the model fitted from fregre.plm() function. A sample test of the last 50 curves of absorbance (or one of the two first derivatives) and Water content can be used to predict the Fat content. We provide below the complete code for the prediction process. R> newy <- matrix(tecator$y$Fa[-ind], ncol = 1) R> newX.d1 <- fdata.deriv(absorp[-ind, ], nbasis = 19, nderiv = 1) R> newX.d2 <- fdata.deriv(absorp[-ind, ], nbasis = 19, nderiv = 2) R> res.basis2 <- fregre.basis.cv(X.d2, y, type.basis = "bspline") R> pred.basis2 <- predict.fregre.fd(res.basis2, newX.d2) R> res.np2 <- fregre.np.cv(X.d1, y, metric = semimetric.deriv) R> pred.np2 <- predict.fregre.fd(res.np2, newX.d1) R> newldata <- list("df" = newdataf, "X.d1" = newX.d1, "X.d2" = newX.d2) R> f1 <- Fat ~ Water + X.d1 R> basis.x1 <- list(X.d1 = basis1) R> basis.b1 <- list(X.d1 = basis2) R> res.lm1 <- fregre.lm(f1, ldata, basis.x = basis.x1, basis.b = basis.b1) Journal of Statistical Software 25 Function df R2S2 RMEP fregre.basis(X.d1, Fat) 6.0 0.928 11.470 0.0626 fregre.basis.cv(X.d2, Fat) 12.0 0.965 5.817 0.0566 fregre.pc(X.d1, Fat) 7.0 0.950 7.975 0.0580 fregre.pc(X.d2, Fat) 6.0 0.954 7.239 0.0556 fregre.pls(X.d1, Fat) 8.4 0.951 7.928 0.0567 fregre.pls(X.d2, Fat) 6.5 0.962 6.015 0.0487 fregre.lm(Fat ~ X.d1 + Water) 7.0 0.987 2.140 0.0097 fregre.lm(Fat ~ X.d2 + Water) 7.0 0.986 2.251 0.0119 fregre.np(X.d1, Fat) 59.3 0.987 3.037 0.0220 fregre.np(X.d2, Fat) 68.1 0.996 1.128 0.0144 fregre.plm(Fat ~ X.d1 + Water) 61.0 0.996 0.914 0.0090 fregre.plm(Fat ~ X.d2 + Water) 66.0 0.997 0.699 0.0115 Table 1: Results for functional regression models. df degrees of freedom, R2,S2 Rresidual variance, and mean square error of prediction (MEP). R> pred.lm1 <- predict.fregre.lm(res.lm1, newldata) R> res.plm1 <- fregre.plm(f1, ldata) R> pred.plm1 <- predict.fregre.plm(res.plm1, newldata) We make predictions for the rest of models fitted in this paper (code not shown). Following the ideas by Aneiros-P´erez and Vieu (2006), we calculated the mean square error of prediction (MEP): MEP =Pn i=1 (yi−ˆyi)2/n/(Var (y)), which is used for comparing the predictions of different fitted models. Table 1resumes the statistics of the fitted models and their predictions. 4. Conclusion The package fda.usc presented in this paper is the result of the integration of our codes with other procedures from different authors, such as the package fda or the functions from the STAPH group. One major advantage of this software is that it avoids the need of a basis representation of functional data. Using the new class “fdata”, the proposed methods can represent the functional data using discretized versions in a given grid of points. The fda.usc package includes most of the methods recently developed for exploratory functional data analysis and for functional regression with scalar response. This package also incorporates other utilities for statistical computing within the field of functional data analysis (FDA). Some useful additions are:  Generalized functional linear models (FGLM): fregre.glm().  Functional analysis of variance: anova.RPm().  Functional supervised classification: classif.knn(),classif.kernel(), and classif.glm().  Functional non-supervised classification: kmeans.fd().