Skip to content

ENH: Gaussian process regression - #4691

Merged
kshedden merged 28 commits into
statsmodels:masterfrom
kshedden:processreg
May 3, 2019
Merged

kshedden merged 28 commits into
statsmodels:masterfrom
kshedden:processreg

Conversation

@kshedden

Copy link
Copy Markdown
Contributor

This is an implementation of maximum likelihood joint estimation of mean and covariance structures for clustered data, using gaussian process-style covariance specifications.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert when merging 3bd98db into 6611e87 - view on lgtm.com

new alerts:

  • 1 for Encoding error

Comment posted by lgtm.com

@coveralls

coveralls commented May 28, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.001%) to 84.531% when pulling ace2c0c on kshedden:processreg into 1246e75 on statsmodels:master.

@codecov-io

codecov-io commented May 28, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4691 into master will increase coverage by 0.01%.
The diff coverage is 82.03%.

Impacted file tree graph

@@            Coverage Diff            @@
##           master   #4691      +/-   ##
=========================================
+ Coverage   81.98%     82%   +0.01%     
=========================================
  Files         588     590       +2     
  Lines       93151   93512     +361     
  Branches    10325   10368      +43     
=========================================
+ Hits        76371   76681     +310     
- Misses      14406   14430      +24     
- Partials     2374    2401      +27
Impacted Files Coverage Δ
statsmodels/regression/tests/test_processreg.py 100% <100%> (ø)
statsmodels/regression/process_regression.py 76.45% <76.45%> (ø)
statsmodels/tools/tests/test_decorators.py 90.9% <0%> (-5.1%) ⬇️
statsmodels/tools/decorators.py 88% <0%> (-2.15%) ⬇️
statsmodels/tsa/ar_model.py 91.26% <0%> (ø) ⬆️
statsmodels/graphics/gofplots.py 82.35% <0%> (ø) ⬆️
statsmodels/stats/proportion.py 87.59% <0%> (ø) ⬆️
statsmodels/base/data.py 90.44% <0%> (ø) ⬆️
statsmodels/regression/linear_model.py 87.17% <0%> (ø) ⬆️
statsmodels/tsa/arima_model.py 86.87% <0%> (ø) ⬆️
... and 6 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 1246e75...2f741fe. Read the comment docs.

@kshedden

kshedden commented Jun 6, 2018

Copy link
Copy Markdown
Contributor Author

@josef-pkt

Copy link
Copy Markdown
Member

@kshedden How soon do you want to merge this?
I would like to review this especially with respect to where it fits in and whether it can be more "standard statsmodels". But that requires that I switch out of my current topic, and get into this topic.

Do you have a notebook example?
Is this for panel/clustered data like a specific MLE version of GEE-Gaussian?
Does this have a nonparametric component like partial linear model or GAM for Gaussian?

I only skimmed parts of the PR.
The model itself looks fine, but I'm thinking about how we can get more consistency and reusable components across models and features that are still to come.

@kshedden

kshedden commented Jun 6, 2018

Copy link
Copy Markdown
Contributor Author

No big rush on this.

It's fully maximum likelihood, so different from GEE-Gaussian where the covariance parameters are estimated separately and plugged in.

I will try to add an example.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 2 alerts when merging 91353eb into 4c601f6 - view on LGTM.com

new alerts:

  • 2 for Except block handles 'BaseException'

Comment posted by LGTM.com

@kshedden

Copy link
Copy Markdown
Contributor Author

@josef-pkt, I would like to merge this soon if no objections. I have used it a lot and it has held up pretty well.

@josef-pkt

Copy link
Copy Markdown
Member

Do you have an example with usage?

There are no unit tests for predict which might be an important application.
I don't know how well the other inherited methods work.

@josef-pkt

Copy link
Copy Markdown
Member

I'm trying out the formula test case

for t_test to work, I need to patch the results/model instance (f is results instance)

# monkey patch
f.model.data.param_names[:] = f.model.exog_names_full
f.df_resid = f.model.endog.shape[0] - len(f.params)

f.t_test(np.eye(len(f.params)))

Is there a reason why summary does not show a full params table (i.e. zvalues and confint)?

@kshedden

Copy link
Copy Markdown
Contributor Author

Here is a simulation that shows how this can be used:

import statsmodels.api as sm                                                                                                                 
import numpy as np                                                                                                                           
import pandas as pd                                                                                                                          
from statsmodels.regression.process_reg import ProcessRegression                                                                                                    
                                                                                                                                             
#                                                                                                                                            
# Simulate longitudinal data                                                                                                                 
#                                                                                                                                            
                                                                                                                                             
n_person = 200                                                                                                                               
                                                                                                                                             
# Ages (standardized)                                                                                                                        
p = 5                                                                                                                                        
ages = np.linspace(-0.5, 0.5, p)                                                                                                             
                                                                                                                                             
# Person id                                                                                                                                  
pid = np.kron(np.arange(n_person), np.ones(len(ages)))                                                                                       
                                                                                                                                             
agesv = np.kron(np.ones(n_person), ages)                                                                                                     
df = pd.DataFrame({"pid": pid, "age": agesv})                                                                                                
                                                                                                                                             
# A couple of covariates                                                                                                                     
df["x1"] = np.random.normal(size=df.shape[0])                                                                                                
df["x2"] = np.random.normal(size=df.shape[0])                                                                                                
                                                                                                                                             
# Mean struture                                                                                                                              
df["Ey"] = 3 * df.age + df.x1 - df.x2                           

# Errors                                                                                                                                     
cmat = np.exp(-3 * np.subtract.outer(ages, ages)**2)                                                                                         
cmatr = np.linalg.cholesky(cmat)                                                                                                             
df["e"] = np.random.normal(size=df.shape[0])                                                                                                 
df["e"] = df.groupby("pid")["e"].transform(lambda x: np.dot(cmatr, x))                                                                       
                                                                                                                                             
# Make the errors heteroscedastic with respect to age                                                                                        
df.e *= np.exp(0.5 + 0.5 * df.age)                                                                                                           
                                                                                                                                             
# The outcome                                                                                                                                
df["y"] = df.Ey + df.e                                                                                                                       
                                                                                                                                             
#                                                                                                                                            
# Fit a Gaussian process regression model                                                                                                    
#                                                                                                                                            
                                                                                                                                             
pr = ProcessRegression.from_formula(                                                                                                         
    "y ~ age + x1 + x2",                                                                                                                     
    data=df,                                                                                                                                 
    scale_formula="1 + age",                                                                                                                 
    smooth_formula="1",                                                                                                                      
    time="age",                                                                                                                              
    groups="pid")                                                                                                                            
                                                                                                                                             
f = pr.fit(verbose=True)                                                                                                                     
                                                                                                                                             
# Get the covariance at the given set of ages for one person (in this case,                                                                  
# the covariance doesn't depend on x1 or x2).                                                                                                
dx = pd.DataFrame({"age": ages, "x1": 0, "x2": 0})                                                                                           
c = f.covariance(ages, dx, dx)                                                                                                               
s = np.sqrt(np.diag(c))                                                                                                                      
                                                                                                                                             
# cr should match cmat above                                                                                                                 
cr = c / np.outer(s, s)                                          

@kshedden kshedden changed the title WIP: Gaussian process regression ENH: Gaussian process regression Aug 23, 2018
@josef-pkt

Copy link
Copy Markdown
Member

the only problem on travis that I can see is one unrelated XPASS in one environment

XPASS statsmodels/tsa/tests/test_holtwinters.py::TestHoltWinters::()::test_forecast Optimizer does not converge

@josef-pkt

Copy link
Copy Markdown
Member

comparing to GEE

mod_gee = GEE.from_formula(                                                                                                         
    "y ~ age + x1 + x2",                                                                                                                     
    data=df,
    cov_struct=Autoregressive(),
    time="age",
    groups="pid")   

res_gee = mod_gee.fit()


f.params[:4]
array([ 0.08719848,  3.01837236,  1.0001811 , -1.00344185])

res_gee.params[:4].values
array([ 0.10859566,  3.01152248,  0.99128876, -1.0265334 ])

f.bse[:4]
array([ 0.08245378,  0.13888817,  0.00799241,  0.00826091])

res_gee.bse[:4].values
array([ 0.08401851,  0.17910797,  0.03066115,  0.02935346])

bse with cov_type='naive':
array([ 0.06862625, 0.15761036, 0.04708175, 0.04510062])

There will be a few more comments for changes, e.g. add fittedvalues and resid to results instance, which I guess have the standard definition as predict() and endog - predict()

I'm still trying to understand this a bit better.
I'm a bit suspicious that this is not the standard definition of gaussian process regression (in machine learning) and might be confusing.
AFAIU at the moment, the mean part is fully parametric and only the covariance matrix uses kernel smoothing, while the gaussian process literature that I read at some point in the past has non-parametric mean function.

@kshedden

Copy link
Copy Markdown
Contributor Author

The covariance matrix is also parametric. The whole thing is a finite dimensional (parametric) MLE, joint for mean and covariance. The parameterization of the covariance matrix is taken from Paciorek and Schervish, but the implementation would easily allow for other parametric covariance models, e.g. AR or Matern.

@josef-pkt

Copy link
Copy Markdown
Member

It reminds me a bit of Stata's xtgls https://www.stata.com/manuals13/xtxtgls.pdf except that you have an MLE version.
(I'm not sure the panel structure is the same.)

I think it might be better to find a name that indicates MLE with heteroscedasticity and correlation.

I also compared with ols with cluster robust standard errors (differences look about in the same range as changing seeds for random. gp might have on average smaller bse, and it should have a bit more accurate mean parameter estimates)

print(res_params[['gp', 'gee', 'ols_clu']])
                 gp       gee   ols_clu
Intercept -0.088851 -0.118358 -0.141672
age        3.086883  3.151059  3.144054
x1         0.991686  1.036157  1.052531
x2        -0.999892 -1.008728 -0.973851

print(res_bse[['gp', 'gee', 'ols_clu']])
                 gp       gee   ols_clu
Intercept  0.086800  0.095815  0.098896
age        0.144355  0.170899  0.179226
x1         0.007359  0.026480  0.057512
x2         0.007481  0.026812  0.054075

The covariance matrix is also parametric. The whole thing is a finite dimensional (parametric) MLE, joint for mean and covariance.

I don't understand the parametric covariance part.
If the scale_formula has a continuous variable in it, then it is using a nonparametric kernel (co)variance function, doesn't it?
update: I guess I see, ProcessRegression.covarince is not smoothing estimated residuals covariances, it constructs a parameteric model based on the scale exog.

The GaussianProcessRegression terminology is really confusing me.
e.g. compared to Rasmussen and Williams http://www.gaussianprocess.org/gpml/chapters/RW2.pdf which I read maybe 8 to 10 years ago.
and http://scikit-learn.org/stable/modules/gaussian_process.html

Comment thread statsmodels/regression/process_reg.py Outdated
raise ValueError("groups is a required argument")

if subset is not None:
warnings.Warn("'subset' is ignored")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pydev is red here and lines 308, 646, 649
Warn shouldn't be capitalized

Comment thread statsmodels/regression/process_reg.py Outdated
score[0:pm] += np.dot(self.exog[ix, :].T, dcr)

# The derivatives for the standard deviation parameters.
rx = np.outer(resid[ix], resid[ix])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My guess is that repeated indexing here is costly.
It would be better to get the indexed array once and keep it during the iteration in the loop
e.g. use resid_i = resid[ix] at the beginning of the loop
similarly with other arrays that don't change during the loop iteration, e.g. sd[ix], sm[ix] are used 4 times each

(I'm spot checking not reviewing line by line)

@josef-pkt

Copy link
Copy Markdown
Member

maybe something like ProcessHetMLE instead of ProcessRegression
I added GLSHet, which only allows for heteroscedasticity but not correlation.
so Het is not really correct in this case, I would like to use it also for GLMHet with only heteroscedasticity. #4730

maybe a name with Panel in it, or whatever a more generic, short statistics term would be, e.g. cluster

I read the description in the ProcessRegression more carefully, and it is clearly written, it's just the use of an unqualified Process in the name that is misleading.
I need to look at the article, but Process seems to be just an implementation detail because we have a distance function without assuming a fixed grid in the cov_resid assumption.
maybe something like ProcessCovMLE (or ClusterProcessCovMLE :)
ProcessCovMLE sounds explicit enough, especially if it moves or is categorized in the docs as Panel data model. (MixedLM doesn't specify either that the core structure is for one-way panel/groups)

@josef-pkt

Copy link
Copy Markdown
Member

I'd like to have MLE in the name to distinguish it methodologically from GLS and GEE/QIF/GMM approaches which could support the same underlying cluster covariance.

Comment thread statsmodels/regression/process_reg.py Outdated

from scipy.stats.distributions import norm
df["t"] = df.coef / df["std err"]
df["P>|t|"] = norm.cdf(2 * (1 - np.abs(df.t)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this correct?
shouldn't this be the usual 2 * norm.sf(np.abs(f.tvalues))

@bashtage

bashtage commented May 3, 2019

Copy link
Copy Markdown
Member

LGTM.

@kshedden
kshedden merged commit 14855d9 into statsmodels:master May 3, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants