Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leave one out cross validation #101

Merged
merged 12 commits into from
Feb 8, 2017
Merged

Leave one out cross validation #101

merged 12 commits into from
Feb 8, 2017

Conversation

mortonjt
Copy link
Collaborator

@mortonjt mortonjt commented Jan 26, 2017

There are a few things that are added to this PR namely

  • percent_explained : calculates the percentage of the total variance explained for each balance axis (think about the analogue for principal components).

  • leave one out cross validation : calculates model error on training dataset and prediction error on testing dataset

  • leave one variable out cross validation : calculates R^2 and model error when each variable is left out of the model. This gives us an idea about the variable importance for each variable. But more work concerning effect size of each variable will need to be done in the future

In addition, the OLS procedure was slightly optimized to reduce the amount of formula -> matrix conversions that needed to be computed. Will need to propagate this to the remaining methods. Thanks @Josh-Lefler for discovering this!

Remember, this is the last major PR that needs to be merged in. Reviews will be greatly appreciated. Thanks!

@coveralls
Copy link

Coverage Status

Coverage increased (+0.05%) to 98.142% when pulling 129f81c on mortonjt:loo into abee6d8 on biocore:master.

Copy link
Member

@josenavas josenavas left a comment

Choose a reason for hiding this comment

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

Thanks @mortonjt ! This looks really good. Note however that my knowledge on the math behind is rather limited, so I just checked style and small changes that can improve the code. Nothing blocking though.

def _fit_ols(y, x, **kwargs):
""" Perform the basic ols regression."""
exog_data = x
submodels = []
Copy link
Member

Choose a reason for hiding this comment

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

Minor, and it depends on how big len(y.columns) is but this can be written as:

submodels = [smf.OLS(endog=y[b], exog=x, **kwargs) for b in y.columns]

Appending to a list may take more than expected if the list is really long.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I didn't know that. Thanks!

@@ -298,3 +318,144 @@ def r2(self):

sst = sse + ssr
return 1 - sse / sst

@property
def mse(self):
Copy link
Member

Choose a reason for hiding this comment

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

Is this property described somewhere (i.e. doc)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'll add it in. It is a measure of Mean of Sum of Squares Error, which is used for calculating R^2 and the cross validation statistics.

fit
"""
params = {'fit_regularized': False}
for key in params:
Copy link
Member

Choose a reason for hiding this comment

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

Are you expecting to grow params in the future? As it is, this for loop only executes one operation so I don't see the point of having it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The main reason for having the kwargs argument was to pass these into the fit function, which have a ton of parameters in them. One advantage of doing this is if the fit function in statsmodels changes, we aren't forced to change our APIs to fit their changes.

columns=exog_names)
results = pd.DataFrame(index=self.balances.index,
columns=['mse', 'pred_err'])
i = 0
Copy link
Member

Choose a reason for hiding this comment

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

I think there are 2 more pythonic way of doing this is, I'm unsure which one is the best for your case. Since i is just an index, this should work:

for sample_id, (inidx, outidx) in zip(self.balances.index, cv_iter):
   etc...

However, If you still need i for something else that I may be missing, then this is the pythonic way of doing the index counting:

for i, (inidx, outidx) in enumerate(cv_iter):
    ....

And remove the i+=1 from the end of the for loop.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Will use enumerate instead. Thanks!


Parameters
----------
regularized : bool
Copy link
Member

Choose a reason for hiding this comment

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

regularized is not named parameter of this function

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'll move this up to the params section. We do actually need this

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Scratch that. I'll delete it.

"""

params = {'regularized': False}
for key in params:
Copy link
Member

Choose a reason for hiding this comment

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

Same comment as above regarding the for loop.

results = pd.DataFrame(index=exog_names,
columns=['mse', 'Rsquared'])
i = 0
for inidx, outidx in cv_iter:
Copy link
Member

Choose a reason for hiding this comment

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

Same comment as above regarding the usage of the i variable.

# The L1 regularization either has numerical issues
# or is random ...
res_coefs = res.coefficients()
pdt.assert_index_equal(exp_coefs.index, res_coefs.index)
Copy link
Member

Choose a reason for hiding this comment

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

Minor and I'm unsure if it applies in the pandas testing functions: in general we use assert*(observed, expected), but I'm unsure if the pandas error messages are expecting this convention.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Going to remove this test since we won't be needing it.

'y1': [-2.074816e+10, -2.039271e+09, -1.843143e+09,
2.261170e+10, -7.925699e+07]
}, index=['Intercept', 'x1', 'x2', 'x3', 'x4']).T
# The L1 regularization either has numerical issues
Copy link
Member

Choose a reason for hiding this comment

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

From my ignorant view, if it is random, can you set a seed? Otherwise, can you test some of the values up to a certain decimal position?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

So this is actually depending on statsmodels/statsmodels#3393

Not sure what is going on there - but maybe we shouldn't include any regularization fitting here until that issue gets resolved. I'm going to remove those fits in the next commit.

for s in self.submodels:
# assumes that the underlying submodels have implemented `fit`.
m = s.fit(**kwargs)
if regularized:
m = s.fit(**kwargs)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is backwards. This should be fit_regularized, not fit. I'm removing the fit_regularized functionality for the time being to resolve this. But this actually messed up the test_mse test. I have fixed that in the upcoming commit

@josenavas
Copy link
Member

Once tests pass

@coveralls
Copy link

Coverage Status

Coverage increased (+0.1%) to 98.229% when pulling ae53632 on mortonjt:loo into abee6d8 on biocore:master.

@mortonjt mortonjt mentioned this pull request Jan 28, 2017
@mortonjt
Copy link
Collaborator Author

mortonjt commented Feb 8, 2017

@sjanssen2 @qiyunzhu could you review / merge? Thanks!

Copy link
Collaborator

@qiyunzhu qiyunzhu left a comment

Choose a reason for hiding this comment

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

Good job! Minor comments.

""" Perform the basic ols regression."""
# mixed effects code is obtained here:
# http://stackoverflow.com/a/22439820/1167475
submodels = [smf.OLS(endog=y[b], exog=x, **kwargs) for b in y.columns]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe these two lines can be merged into one? (Not sure if what I proposed is Pythonic, if not sorry.)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

meh sure.

# assumes that the underlying submodels have implemented `fit`.
m = s.fit(**kwargs)
self.results.append(m)
def fit(self, regularized=False, **kwargs):
Copy link
Collaborator

Choose a reason for hiding this comment

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

So this rewritting is basically an optimization of the old function. Is that right?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yup!

columns=['mse', 'Rsquared'])
for i, (inidx, outidx) in enumerate(cv_iter):
feature_id = exog_names[i]
res_i = _fit_ols(endog, exog.loc[:, inidx], **kwargs)
Copy link
Collaborator

Choose a reason for hiding this comment

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

This part is bit awkward to me. res_i is defined twice with different data types. Is this Pythonic?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

ok, I'll rename it

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Basically, all this is doing is

  1. Retrieving the model specifications for the linear regression (model_i)
  2. Actually fitting the model with a numerical optimization (res_i)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Sounds good!

results.loc[feature_id, 'Rsquared'] = 1 - sse / sst
# degrees of freedom for residuals
dfe = res_i[0].df_resid
results.loc[feature_id, 'mse'] = sse / dfe
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can this dfe be zero?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If that ever happens, would indicate overfitting to the extreme (i.e. more parameters than data points). I think it is safe to say that this will never happen.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Got it!

# Using sum of squares error calculation (df=1)
# instead of population variance (df=0).
axis_vars = np.var(self.balances, ddof=1, axis=0)
return axis_vars / axis_vars.sum()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can this axis_vars.sum() be zero?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

That would mean that the variance is zero. For practical reasons, that will not happen.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I see.

@coveralls
Copy link

Coverage Status

Coverage increased (+0.1%) to 98.22% when pulling 89d7810 on mortonjt:loo into abee6d8 on biocore:master.

@coveralls
Copy link

Coverage Status

Coverage increased (+0.1%) to 98.22% when pulling 89d7810 on mortonjt:loo into abee6d8 on biocore:master.

@coveralls
Copy link

Coverage Status

Coverage increased (+0.1%) to 98.22% when pulling 89d7810 on mortonjt:loo into abee6d8 on biocore:master.

@qiyunzhu qiyunzhu merged commit 173bf10 into biocore:master Feb 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants