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

Proposal: support columns representing multiple features #149

Open
MartinStancsicsQC opened this issue Jul 31, 2023 · 3 comments
Open

Proposal: support columns representing multiple features #149

MartinStancsicsQC opened this issue Jul 31, 2023 · 3 comments
Assignees
Labels
enhancement New feature or request question Further information is requested

Comments

@MartinStancsicsQC
Copy link

MartinStancsicsQC commented Jul 31, 2023

First of all, thanks for the amazing package! I am working on extending a GLM package (glum) and the matrix library it uses as a backend (tabmat) with a formula interface, and formulaic is a great fit so far.

The only pain point we have is related to the handling of categorical columns, which can represent multiple features during model estimation*. Ideally, for such a column, we would like to have column names in ModelSpec.structure as if those categoricals were one-hot encoded, even though they are not. We did find a way to make it work (draft PR), but the current solution feels somewhat hacky, and we are overriding long methods just so we can change a couple of lines.

Would it make sense for formulaic to add more support for these kinds of columns? I'm thinking of some kind of interface through which a column can tell formulaic how many feature it represents and what their names are, and then _build_model_matrix and _enforce_structure could take those into account when constructing and checking the EncodedTermStructure. I think such a solution would be useful not only for our packages, but potentially many others, too (e.g. GLMs in H2O.ai and certain scikit-learn estimators have native categorical support, too. Also, might a potential solution be related to issue #46, too?

If you think such a feature would be in-scope for formulaic, I would be more than happy to help implement it.

* glum and tabmat allow matrix operations and model estimation without one-hot-encoding categorical columns. This has performance benefits over having potentially thousands of indicator variables.

@matthewwardrop
Copy link
Owner

matthewwardrop commented Aug 12, 2023

Hi @MartinStancsicsQC !

Thanks for reaching out, and apologies for the delay. It's exciting to see the extensibility of formulaic being exploited in the wild! And I'm more than happy to extend Formulaic's support for these kinds of use-cases.

One thing I didn't fully understand is why you want to treat a categorical column as if it were one-hot encoded when it was not. Why not just encode the column directly as a categorical/factor column, and then let tabmat take care of it directly? We'd need a tiny amount of extra metadata for the structure enforcement, but otherwise this should work just fine. Today you can achieve most of this passthrough (modulo enforcement) by just wrapping your incoming vector in a FactorValues(...) class, and indicating that they are already encoded. We can make this more naturally a part of the categorical coding functionality using something so you can do something like C(X, contr.none).

In [1]: import pandas; from formulaic import FactorValues, model_matrix

In [2]: df = pandas.DataFrame({'X': ['a', 'b', 'c', 'a', 'b', 'c']})

In [3]: model_matrix("FactorValues(X, encoded=True)", df)
Out[3]:
   Intercept FactorValues(X, encoded=True)
0        1.0                             a
1        1.0                             b
2        1.0                             c
3        1.0                             a
4        1.0                             b
5        1.0                             c

We can extend FactorValues with a factor_levels attribute that we can check during structure enforcement, which would be populated by C.

Would that work for you? Or is there something I am missing? If not, I can have this added in the next patch release :).

@matthewwardrop matthewwardrop self-assigned this Aug 12, 2023
@matthewwardrop matthewwardrop added enhancement New feature or request question Further information is requested labels Aug 12, 2023
@MartinStancsicsQC
Copy link
Author

MartinStancsicsQC commented Aug 14, 2023

Hey @matthewwardrop, thanks so much for the response. I really like the idea of FactorValues having some metadata about categorical levels, which can be set in C() or encode_contrasts. Let me elaborate a bit on our use case to make sure I understand the proposed solution :)

First, let me clarify the need for encoding, because I now realize that I've omitted an important piece of information: the materializer we are building takes a pandas.DataFrame as its input, and outputs a tabmat.MatrixBase object. So each pandas column has to be encoded in the sense of being converted to the appropriate tabmat column type. In the case of categoricals, it happens here, and I think this conversion fits very nicely into formulaic's structure. The only discrepancy is that formulaic sees the resulting object as one column, while tabmat treats it as a set of dummies (e.g., tabmat.CategoricalMatrix(["a", "b", "a"]).shape == (3, 2) as opposed to pandas.Categorical(["a", "b", "a"]).shape == (3, )).

Now, if I understand your idea correctly, encode_contrasts would be able to set some metadata about which dummy columns a tabmat categorical matrix actually represents (i.e. factor_levels), and _enforce_structure would perform its checks based on that. If that is the case, I think that would be a very nice solution to one part of this problem.

It would also be super useful if the ModelSpec.structure would then be populated based on this metadata (so that, for example, ModelSpec.column_names can be used as coefficient names later on). I'm thinking of something like

...

            spec = spec.update(
                structure=[
                    EncodedTermStructure(
                        term,
                        [st.copy(without_values=True) for st in scoped_terms],
                        list(
                            itertools.chain.from_iterable(
                                _name_columns(name, value) for name, col in scoped_cols.items()
                            )
                        ),
                    )
                    for term, scoped_terms, scoped_cols in cols
                ],
            )

...

def _name_columns(name, col):
    if value.__formulaic_metadata__.factor_levels is not None:
        for level in col.__formulaic_metadata__.factor_levels:
            yield col.__formulaic_metadata__.name_format.format(name, level)
    else:
        yield name

replacing these lines. How does that look to you? (Apologies if something does not make sense, I'm still in the process of getting my head around the internals of formulaic.)

It's also perfectly fine for us to to make these changes downstream if you think it is too specific functionality, or you'd like to have them tried out somewhere before adding them to formulaic.

@matthewwardrop
Copy link
Owner

matthewwardrop commented Sep 25, 2023

Sorry for the latency. Life has been pretty hectic recently. This is going to miss the next patch release of formulaic, but I have read through this again and portions of tabmat and I think I understand what is going on.

Firstly, tabmat looks awesome. Kudos to you for your work there. I might even pick it up and start playing with it in some compressed regression routines I built. And as I've said before, I'm excited that Formulaic is proving useful and extensible in the way I had hoped.

Secondly, adding support for these kind of data structures makes a lot of sense to me. I'll noodle on how to best integrate it, but I do have some follow up questions (which might be answered by digging into tabmat more... but perhaps it is more expedient to simply ask): How do interaction terms work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants