Skip to content

ENH - multiple response categorical variables - #3378

Open
gjlondon wants to merge 58 commits into
statsmodels:mainfrom
gjlondon:ENH-multiple-response-categorical-variables
Open

gjlondon wants to merge 58 commits into
statsmodels:mainfrom
gjlondon:ENH-multiple-response-categorical-variables

Conversation

@gjlondon

Copy link
Copy Markdown

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:

  1. Bonferroni corrected
  2. Second order Rao Scott corrected
  3. Bootstrapping

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:

  1. 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 Factor class 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 like ContingencyTableFactor.)

  2. 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 MRCVTable constructor 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)

Comment thread statsmodels/stats/contingency_tables.py Outdated
return dataframe


class MRCVTable(object):

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.

the name is not informative enough, it's difficult (impossible) to remember what MRCV stands for

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed. Changed to MultipleResponseContingencyTable...I thought about ContingencyTableWithMultipleResponseVariables or MultipleResponseCategoricalVariableContingencyTable but those seem too long.

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.

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.

@josef-pkt

Copy link
Copy Markdown
Member

Thanks,
I had just a very brief look.

some formal stuff

  • we have a 80 character per line limit
  • we don't want to add generated output in notebooks to the repository to avoid the additional increase in size (memory of history) from the generated output (although we lose seeing the output right away). Notebooks like yours are very helpful for the documentation, but during development it is better to keep them in a gist or a private scratch/misc repository, and just post the link in a comment.
  • method names are too long _test_for_single_pairwise_mutual_independence_using_rao_scott_2. First it's more difficult to read (although easier to understand), but given the 80 character line limit, one method name would already exceed it with a few indentation.

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 api.py or wherever they belong for user access.

I will try to at least skim the code to see if the general structure is fine.

@josef-pkt josef-pkt left a comment

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.

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?

Comment thread statsmodels/stats/contingency_tables.py Outdated
----------
table_p_value : float
If repeated samples were drawn from the underlying population
and the row and column variables were in fact independent,

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.

This should be a relatively short description, explanations can be in the Notes section, if needed we can add "see Notes"

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.

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)

Comment thread statsmodels/stats/contingency_tables.py Outdated
try:
str_function = unicode
except NameError: # Python 3 no longer has the unicode() function
str_function = str

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.

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

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.

empty line before section headers


Parameters
----------
row_factors : a Factor instance or list of Factors

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.

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

Comment thread statsmodels/stats/contingency_tables.py Outdated
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

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.

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.)

Comment thread statsmodels/stats/contingency_tables.py Outdated
def test_for_independence(self, method="bonferroni"):
"""
Test whether the variables on the rows and columns of this
contingency table are statistically independent.

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.

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.

Comment thread statsmodels/stats/contingency_tables.py Outdated
method : {'bonferroni', 'rao-scott-2'}
The method to use in testing for independence.

The "Bonferroni" method is simpler and more transparent and can

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.

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.)

Comment thread statsmodels/stats/contingency_tables.py Outdated
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,

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.

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

Comment thread statsmodels/stats/contingency_tables.py Outdated
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:

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.

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.)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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?

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.

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 ?).

Comment thread statsmodels/stats/contingency_tables.py Outdated

Parameters
----------

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.

no empty line

@josef-pkt

Copy link
Copy Markdown
Member

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)
Also pandas Multi-Index sounds similar and might be useful for pivoting.
(just guessing since I haven't looked closely enough)

@josef-pkt

Copy link
Copy Markdown
Member

The documentation notebook looks good.
In the Monte Carlo, the test seems to under reject a bit.
normed=True histogram would be better, if pandas supports the keyword
also (p_value_series < 0.05).mean() would calculate the rejection fraction (at least if it where an array.

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.

@josef-pkt

Copy link
Copy Markdown
Member

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

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.

no plain assert in unit tests, either use generic np.testing.assert_ or a specific assert_xxx, e.g. assert_array_less.

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.

(the reason is that plain python asserts are removed if python is "compiled" with -o

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

good to know!

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)

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.

assert_equal
and similar in other unit tests

@josef-pkt

Copy link
Copy Markdown
Member

It looks like you didn't add presidential_survey_filtered.csv to a commit

@gjlondon

Copy link
Copy Markdown
Author

Thanks for the quick review and responses.

I...

  1. narrowed all the lines to fit in the 80 char limit

  2. moved the notebooks to a supplemental repo.

  3. Shortened some method names. Let me know if you'd like them to be even shorter. My preference is to make the names as readable as possible within space constraints and I worry that contracting them anymore requires contractions like "bonf" which make the logic more opaque (and it's already pretty opaque...)

  4. Committed the presidential2016 data and the csv files where I'm keeping test baselines from R

  5. Looked for places to combine functions to cut down the number. Didn't find much...there's a lot of code that looks superficially similar but actually has subtle differences, e.g. code paths that return two values in one case and one value in another, or that iterate over one axis in one case and two axes in another. I might be able to jam some of those together but it would require a lot of parameterization and branching and would probably end up making the overall code even less clear. If you spot any specific examples of code that could be consolidated please let me know.

  6. shortened parameter descriptions and moved extra details to Notes

  7. Renamed table_p_value to p_value_overall and cellwise_p_values to p_values_cellwise

  8. Checked parameter names for consistency with the rest of the module. Most other classes/functions take a pre-tabulated table so their parameters are just table or something like that. They don't make any reference to factors so I don't see any naming inconsistency.

  9. Got rid of any single-letter parameters

  10. Made sure each description has a leading one-liner

  11. Replaced the plain asserts with np equivalents.

  12. Got rid of the Py3 detection and used asunicode from compat. Other than that one function, I don't think I'm using anything that behaves differently in 2 vs 3.

  13. refactored the _extract_and_validate function. Gonna just focus on clarity. It seems unlikely anyone is going to be so sensitive to performance that an extra 2 if statements will ruin them.

re: the lots of underscore method, the idea was that the public interface would be very small, i.e. just the initializer for MultipleResponseTable and Factor and the test_for_independence method on the Table. The user can pass a test type (bonferroni or rao scott) into test_for_independence but otherwise the function figures out which tests to run on its own. That seemed better than expecting users to pick through all the many individual methods (and it's also the design that the MRCV library uses). Users can use the private methods directly if they want but they should be aware that the onus is on them to format the data correctly and make the right assumptions.

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!

@josef-pkt josef-pkt added this to the 0.9 milestone Feb 6, 2017
shifted data
"""
if dataframe.min().min() == 0:
return dataframe + 0.5

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.

Do you want to increase all values, or should this just increase the zeros to 0.5?

@josef-pkt josef-pkt left a comment

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.

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.

Comment thread statsmodels/stats/contingency_tables.py Outdated
"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."

@josef-pkt josef-pkt Feb 9, 2017 •

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.

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.

@gjlondon

Copy link
Copy Markdown
Author

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.

@gjlondon

Copy link
Copy Markdown
Author

@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.

@gjlondon
gjlondon force-pushed the ENH-multiple-response-categorical-variables branch from 3373ec5 to 4b24d47 Compare April 27, 2017 23:42
@gjlondon

Copy link
Copy Markdown
Author

(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.
@gjlondon
gjlondon force-pushed the ENH-multiple-response-categorical-variables branch from 1695716 to af4cc3a Compare April 28, 2017 01:27
@josef-pkt josef-pkt modified the milestones: 0.9, 0.10 Apr 22, 2018
@gjlondon

Copy link
Copy Markdown
Author

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
@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert and fixes 1 when merging 192d2f9 into fccc099 - view on lgtm.com

new alerts:

  • 1 for Encoding error

fixed alerts:

  • 1 for Missing call to __init__ during object initialization

Comment posted by lgtm.com

@josef-pkt josef-pkt modified the milestones: 0.10, 0.16 Jul 25, 2025
@josef-pkt

Copy link
Copy Markdown
Member

1800 lines addition of core code, 4000 lines total
I don't remember much of this.
So the review to get this merged will take some time.

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 Model would be multinomial count #8380 #8388 (although restriction here is that each choice can show up at most once),
Group logit (logit/binary with several choice opportunities) would be similar, but that usually assumes that each choice has the same structure, and the corresponding method might condition on the number of choice opportunities.

maybe related:
When I looked at confusion table for multinomial/ordinal models, then predicted probabilities often were not concentrated on a single choice, and seldomly selected choices might never be the max prob choice. A better confusion table with lowered thresholds could have multiple selected choices. (In the confusion table case I switched to evaluating predicted probabilities directly compared to actual choices. This always includes all choices with positive values.)
(Can we have an underlying multivariate latent variable model with thresholds censoring instead of simplex (sum to one) constraints? For example multivariate normal like MNProbit or independent extreme value like MNLogit with regressor dependent means).

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.

2 participants