Repository navigation
Conversation
| return dataframe | ||
|
|
||
|
|
||
| class MRCVTable(object): |
There was a problem hiding this comment.
the name is not informative enough, it's difficult (impossible) to remember what MRCV stands for
There was a problem hiding this comment.
Agreed. Changed to MultipleResponseContingencyTable...I thought about ContingencyTableWithMultipleResponseVariables or MultipleResponseCategoricalVariableContingencyTable but those seem too long.
There was a problem hiding this comment.
We can decide on the final names later, after more review
I guess MultipleResponseTable should be enough, there is already a StratifiedTable, and the module name is already contingency_table.
|
Thanks, some formal stuff
Also, please add a comment about having the permission of the authors of the R package that we can translate and use it under our BSD license. Another consideration: I would like to keep modules to a manageable size if there is no tight integration of different parts. That is, if, as expected, this part still expands and there is no tight or circular connection with the existing contingency table code, then it might be better to start a new module, possibly private with leading underscore and the classes and functions are imported in contingency tables and I will try to at least skim the code to see if the general structure is fine. |
josef-pkt
left a comment
There was a problem hiding this comment.
I stopped reading half way through contingency_table.py and just skimmed the pattern in the second half.
I think, the structure overall looks good.
There are many individual methods. Can some of those be combined without loosing much in terms of modularity. I didn't check if they could share code.
The verbosity with the long names makes it a bit difficult to read for me, i.e. it's more like a novel than something to quickly skim to get the main idea.
One issue is the data structure. The Factor class is fine, but maybe there is something where this can be stream lined e.g. by reusing pandas Categoricals.
(That's mainly an impression, I didn't go through the examples yet.)
In which format is the raw data 0-1 for each of the multiple choices?
| ---------- | ||
| table_p_value : float | ||
| If repeated samples were drawn from the underlying population | ||
| and the row and column variables were in fact independent, |
There was a problem hiding this comment.
This should be a relatively short description, explanations can be in the Notes section, if needed we can add "see Notes"
There was a problem hiding this comment.
e.g. mainly refer to the (joint) hypothesis that row and column variables are independent
to emphasis the difference to the cellwise p-value
another naming convention: we prefer post-fix qualifiers in names to keep the main object in sequence e.g. p_value_joint p_value_cellwise p_value_xxx.
(just example for now, I don't want to suggest names in my first reading, when I have no idea how it fits together)
| try: | ||
| str_function = unicode | ||
| except NameError: # Python 3 no longer has the unicode() function | ||
| str_function = str |
There was a problem hiding this comment.
we have statsmodels.compat to handle this kind of version specific code
| column_factors : a Factor instance or list of Factors | ||
| The factor or factors containing data that you intend to have on the | ||
| columns, (i.e. the y axis) of the contingency table. | ||
| Attributes |
There was a problem hiding this comment.
empty line before section headers
|
|
||
| Parameters | ||
| ---------- | ||
| row_factors : a Factor instance or list of Factors |
There was a problem hiding this comment.
In general (I haven't checked specifically): we need to check names and conventions with other classes in this module, so we get consistency across contingency table objects and functions
| data : a 2-dimensional numpy array or DataFrame | ||
| The raw data from which a contingency table is to be constructed. | ||
| Include only data that you intend to include in the contingency table. | ||
| I : int |
There was a problem hiding this comment.
no single letter names in the API.
(I don't know enough yet to comment on the signature itself, maybe instead of I and J we use lists of column names, or the user provides the two factors in two different dataframes.)
| def test_for_independence(self, method="bonferroni"): | ||
| """ | ||
| Test whether the variables on the rows and columns of this | ||
| contingency table are statistically independent. |
There was a problem hiding this comment.
This needs to be a one line summary description. It's used in tables generated for the documentation.
More text and description can follow after a blank line.
| method : {'bonferroni', 'rao-scott-2'} | ||
| The method to use in testing for independence. | ||
|
|
||
| The "Bonferroni" method is simpler and more transparent and can |
There was a problem hiding this comment.
This might fit better in the Notes section. (Not as important to make the change here because there are no other parameters.
(general idea: users have to go through the description once, but then they just need quick reminders, and we and users don't want to have to read through the full explanation each time. similar reason for shorter method names.)
| return self._test_for_independence_using_bonferroni(columns_are_multiple_response, | ||
| rows_are_multiple_response) | ||
| elif method_lower in ("rao-scott-2", "rao", "rs2", "rs"): | ||
| return self._test_for_independence_using_rao_scott(columns_are_multiple_response, |
There was a problem hiding this comment.
one possibility, especially given that it's an internal name
_test_indep_bonf _test_indep_rs or something like that
for and using in the name don't provide much or any information
| msg = "we don't currently support tables with more than one factor on the columns" | ||
| raise NotImplementedError(msg) | ||
| column_factor = column_factors[0] | ||
| except TypeError: |
There was a problem hiding this comment.
what kind of TypeErrors is this supposed to catch?
the try except in this method look a bit to roundabout. It would be easier to understand if we just handle different cases with ifs. or require conversion to a single format.
(I'm not sure how this should work here, which cases is this supposed to handle.)
There was a problem hiding this comment.
Actually this illustrates a question I meant to ask in the initial PR message -- how do you think about the tradeoff between input validation and performance? The MRCV methods have a few pretty specific requirements for the data (e.g. the frame orientation, using only 0/1's, the number of factors passed). But every if len(x) == 2 type validation check costs some bit of performance.
The idea behind this weird try structure was to avoid doing an if statement to check whether column factor is a Factor instance vs a list (calling len on a Factor instance throws the type error). The idea being that people should mostly be passing in a list (since the param name is pluralized) so in the "default" case you save one validation step (it's my understanding that you don't pay a performance cost for entering a try block as long there's no exception).
I think I probably over-optimized here...using trys instead of ifs will create a very small performance improvement and it makes the code substantially less readable. But at the same time I didn't want to presume that that little bit of performance doesn't matter to the user.
I also thought about maybe adding something like validate=True as a parameter and letting users pass a param to explicitly disable validation checks if they want to squeeze performance. But that also requires complicating the code.
How do you think about the tradeoff?
There was a problem hiding this comment.
just a general answer:
We don't have a strict or clearly defined policy for input verification. Traditionally we have avoided expensive checks in favor of performance and relying on users to do some checks.
However, we do a lot of type conversion in the initial parts of a function or in the data handling of the models. Those are partially cheap and partially a trade-off so we can allow different types of inputs.
If I remember correctly what I was thinking, then this type of input ambiguity or flexibility should be resolved in the __init__ instead of individual methods, so that the methods can really on clearly defined attributes.
For example an isinstance check or check for specific attributes is still cheap relative to the computations that we have in the functions and classes. But in several places we also have keywords for the user to choose the treatment (e.g. missing) or to provide information that avoids the internal check (has_const ?).
|
|
||
| Parameters | ||
| ---------- | ||
|
|
|
about Factor: after looking at the example, I don't think there is anything premade for multiple-response Factors that can be directly used. So Factor seems to be needed. Adding a qualifier to the name might be better MultiFactor? There might be some "cute" solutions for the fully expanded contingency table like encoding from binary to decimal 100010 -> ? to get a standard factor. (0 or 1 for each multiple choice makes a binary number) |
|
The documentation notebook looks good. When you introduce bootstrap I would mention more that chisquare with bonferroni and rao scott is an approximate, large sample distribution, and bootstrap might be more accurate in small samples. |
|
In the notebook you use many private (leading underscore) methods. Is this by design and should they be public methods, or is there an official public interface to use instead? |
| assert rao_p_value >= 0.05 | ||
| bonferroni_test = multiple_response_table._test_for_marginal_mutual_independence_using_bonferroni_correction | ||
| bonferroni_table_p_value, bonferroni_cell_p_values = bonferroni_test(srcv, mrcv) | ||
| assert bonferroni_table_p_value >= 0.05 |
There was a problem hiding this comment.
no plain assert in unit tests, either use generic np.testing.assert_ or a specific assert_xxx, e.g. assert_array_less.
There was a problem hiding this comment.
(the reason is that plain python asserts are removed if python is "compiled" with -o
| multiple_response_questions = presidential_data.iloc[:, 6:] | ||
| table = ctab.MultipleResponseContingencyTable.from_data(multiple_response_questions, 5, 5) | ||
| expected = np.array([44, 49, 15, 22, 12]) # from a manual run | ||
| assert np.all(table.table.values[0, :] == expected) |
There was a problem hiding this comment.
assert_equal
and similar in other unit tests
|
It looks like you didn't add |
|
Thanks for the quick review and responses. I...
re: the lots of underscore method, the idea was that the public interface would be very small, i.e. just the initializer for re: the notebooks...I'll clean them up once the code stabilizes. I wrote them in parallel to designing the API so some of it precedes the public functions 😄 I think that should address all the comments so far...let me know if I missed anything or you see anything else! |
| shifted data | ||
| """ | ||
| if dataframe.min().min() == 0: | ||
| return dataframe + 0.5 |
There was a problem hiding this comment.
Do you want to increase all values, or should this just increase the zeros to 0.5?
josef-pkt
left a comment
There was a problem hiding this comment.
It's too long for me to read through right now. I will try to get back to it next week. I will also have to remind myself what this is supposed to do.
I didn't see any obvious problems while skimming through it. Test coverage also looks good.
So, I think this should soon be ready to merge.
| "I, Natalie Koziol, the original author of the MRCV R package, | ||
| give my permission to include a translation of MRCV in the statsmodels | ||
| library under a BSD or compatible license as long as the | ||
| original software and authors are cited." |
There was a problem hiding this comment.
This needs to go into a copyright file. The detail is not needed for the docstring.
(there is a file "statsmodels\COPYRIGHTS.txt" that is supposed to contain the copyrights of not original code. I haven't looked at it in some time)
For the docstring you could just add "with the permission of the authors" to the first sentence in the Notes section.
|
Thanks for comments so far! I have a few more changes and some minor bug fixes on a branch I'm hoping to merge into this one before this PR gets accepted. Things have gotten a bit crazy at work but hopefully I'll be able to get those in in the next couple of weeks. It might make sense for you to hold off on giving a final until I gotten those commits in. |
|
@josef-pkt sorry for the long delay. I finally got time to integrate my fixes and also add some real documentation. Please take a look when you get a chance and let me know if you see anything else that needs to change. Also, if it's easier to read, I can rollback this branch to where it was before these new commits and then submit the new commits as a PR against the existing branch. |
Using real R results
Getting ready for API refactor.
I was disambiguating duplicate index/column labels in multiple-response contingency tables by appending a ' character. I realized that can cause problems for users (i.e. me!) so I'm allowing passing a custom character. Also, I realized that the pandas `get_dummies` function is better than pivot table for 'rotating' factors so switched to use it.
Also fix failing/broken tests
3373ec5 to
4b24d47
Compare
|
(Also had to rebase against master and force push to get merge-ability back) |
Chi2 tests can't handle having zero expected cell counts. Rather than always refusing to calculate, we let users pass a flag to add 0.5 to each cell count in the item response tables.
1695716 to
af4cc3a
Compare
|
Just checking in if there's anything I can do to help get this across the finish line. |
# Conflicts: # docs/source/contingency_tables.rst # statsmodels/stats/contingency_tables.py # statsmodels/stats/tests/test_contingency_tables.py
|
This pull request introduces 1 alert and fixes 1 when merging 192d2f9 into fccc099 - view on lgtm.com new alerts:
fixed alerts:
Comment posted by lgtm.com |
|
1800 lines addition of core code, 4000 lines total Too much work for 0.15, but it should be a priority target for 0.16, because we don't have anything that covers this case. The closest maybe related: |
Here's my initial port of the MRCV R package into Python. It focuses on the functions from the 2004 Bilder and Loughin paper.
I haven't done proper documentation yet (though I do have docstrings on everything)...I'm hoping to get some initial impressions so I don't spend time documenting details that may change. I did start on a Jupyter notebook that walks through most of the functionality. It's incomplete but you can see it here
I verified that all of the results match the output from the R library for the test dataset I'm using (which is from a survey conducted by my employer in the fall; the data is included as a new dataset). I tried to think of corner cases that would break the functions and covered all the ones I can think of. Please let me know if you think of any other corner cases.
The MRCV library provides three types of tests:
I've only done a partial implementation of the bootstrap method because at a first cut, it was much too slow to use in real time analysis (which is my primary use case). I'm hoping to find a way to make it faster and flesh it out in the future.
A couple implementation decisions I'm not 100% sure about:
All of the tests need to retain the original data to test for independence (i.e. you can't just feed them a pre-tabulated table like you can with the existing Table class). So I introduced a new
Factorclass with some built-in data munging operations and metadata. I'm not sure if that was overkill (or if it should perhaps have a less generic name likeContingencyTableFactor.)In theory, this methodology can be used on three MRCV's at a time (e.g. a table with one row variable and two column variables). I didn't have the bandwidth to handle that case right now. But I want to allow for the possibility in the future. So I'm making the
MRCVTableconstructor accept row_factors and column_factors as a list but then enforcing that each list has only one item. I know that's weird, but I'm not sure how else to do it that allows allowing extra factors in the future without requiring a breaking API change if I do.Thanks for taking a look. I'm very open to whatever feedback you have. Also please let me know if you'd like me to do detailed documentation before you have a first review.
(Also I know the commits are a mess...I'll rebase once I get the thumbs up)