-
Notifications
You must be signed in to change notification settings - Fork 27
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
Conversation
There was a problem hiding this 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.
gneiss/regression/_ols.py
Outdated
def _fit_ols(y, x, **kwargs): | ||
""" Perform the basic ols regression.""" | ||
exog_data = x | ||
submodels = [] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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.
gneiss/regression/_ols.py
Outdated
fit | ||
""" | ||
params = {'fit_regularized': False} | ||
for key in params: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
gneiss/regression/_ols.py
Outdated
columns=exog_names) | ||
results = pd.DataFrame(index=self.balances.index, | ||
columns=['mse', 'pred_err']) | ||
i = 0 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
gneiss/regression/_ols.py
Outdated
|
||
Parameters | ||
---------- | ||
regularized : bool |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
gneiss/regression/_ols.py
Outdated
""" | ||
|
||
params = {'regularized': False} | ||
for key in params: |
There was a problem hiding this comment.
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.
gneiss/regression/_ols.py
Outdated
results = pd.DataFrame(index=exog_names, | ||
columns=['mse', 'Rsquared']) | ||
i = 0 | ||
for inidx, outidx in cv_iter: |
There was a problem hiding this comment.
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.
gneiss/regression/tests/test_ols.py
Outdated
# The L1 regularization either has numerical issues | ||
# or is random ... | ||
res_coefs = res.coefficients() | ||
pdt.assert_index_equal(exp_coefs.index, res_coefs.index) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
gneiss/regression/tests/test_ols.py
Outdated
'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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
gneiss/regression/_ols.py
Outdated
for s in self.submodels: | ||
# assumes that the underlying submodels have implemented `fit`. | ||
m = s.fit(**kwargs) | ||
if regularized: | ||
m = s.fit(**kwargs) |
There was a problem hiding this comment.
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
Addressed @josenavas's comments
Once tests pass |
@sjanssen2 @qiyunzhu could you review / merge? Thanks! |
There was a problem hiding this 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.
gneiss/regression/_ols.py
Outdated
""" 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] |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
- Retrieving the model specifications for the linear regression (
model_i
) - Actually fitting the model with a numerical optimization (
res_i
)
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see.
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!