Skip to content

RandomForest not passing feature names to trees and creating warnings. #26140

Open

Description

@howarth

Describe the bug

I fit a decision forest with training data that includes feature names. When I call predict_proba on the forest everything is fine. When I call rf.estimators_[0].predict_proba it will warn that it was not trained with feature names.

Steps/Code to Reproduce

import numpy as np
from sklearn.ensemble import RandomForestClassifier

print(sklearn.__version__)

data = np.random.normal([1,2,3,4,5,6,7,8,9,10], size=(1000, 10))
feature_names = [f'F{i}' for i in range(10)]
df = pd.DataFrame(data=data, columns=feature_names)
y = np.ones(1000)
y[500:] = 0

rf = RandomForestClassifier()
rf.fit(df, y)

print(f"Feature names in Forest: {rf.feature_names_in_} ")

print('Classing pred proba on forest')
rf.predict_proba(df)
print('Done calling pred proba on forest')

# THIS GIVES A WARNING
rf.estimators_[0].predict_proba(df)

Expected Results

No warnings

Actual Results

Feature names in Forest: ['F0' 'F1' 'F2' 'F3' 'F4' 'F5' 'F6' 'F7' 'F8' 'F9'] 
Classing pred proba on forest
Done calling pred proba on forest
.....lib/python3.8/site-packages/sklearn/base.py:432: UserWarning: X has feature names, but DecisionTreeClassifier was fitted without feature names
  warnings.warn(

Versions

sk>>> sklearn.show_versions()

System:
    python: 3.8.16 (default, Mar  2 2023, 03:21:46)  [GCC 11.2.0]
executable: ....../bin/python
   machine: Linux-5.15.0-60-generic-x86_64-with-glibc2.17

Python dependencies:
      sklearn: 1.2.2
          pip: 23.0.1
   setuptools: 65.6.3
        numpy: 1.23.1
        scipy: 1.9.0
       Cython: None
       pandas: 1.5.3
   matplotlib: None
       joblib: 1.1.1
threadpoolctl: 2.2.0

Activity

  1. added
    Needs Triage
    on Apr 10, 2023
  2. betatim commented on Apr 11, 2023

    @betatim
    Member

    Thanks for reporting this. What happens is that the df you pass in to the random forest has feature names, but these aren't passed on to the individual trees that make up the forest. This means when you directly access a tree and pass it the df it warns about this.

    I think this happens because a lot of the scikit-learn data input validation that goes on in an estimator converts from a dataframe to a numpy array, which is then passed to the individual trees.

    I think it would make sense to pass the feature name along as well so that use cases like your work. It would also mean that errors in the individual trees could make use of the feature names, etc. However, I am not sure how complex it would be to do this.

  3. betatim commented on Apr 11, 2023

    @betatim
    Member

    A simple fix, that I didn't expect to work, would be to set feature_names_in_ for the trees in the fitted forest. Something like the following:

    for est in rf.estimators:
      est.feature_names_in_ = rf.feature_names_in_

    I was expecting this to lead to a warning when the estimators are used from rf.predict_proba but it turns out that input validation is turned off when the trees are used from within the forest. This means this code works.

    Would be good to hear what others think about this, just because there is no warning/exception doesn't mean it is a good idea ;)

  4. removed
    Needs Triage
    on Apr 11, 2023
  5. thomasjpfan commented on Apr 11, 2023

    @thomasjpfan
    Member

    As mentioned in #26140 (comment), RandomForest* is configured to not validate in predict, so we can get away with setting the feature names directly. I'm okay with adjusting RandomForest* to do this.

    For linking purposes, there was a related issue with Bagging* (#21599) that I tried to resolve in #21811. Bagging* is harder because we can not turn off validation in the inner estimator and so we are forced to pass in the DataFrame. Passing in DataFrames lead to issues with the common test: #21811 (comment).

  6. betatim commented on Apr 12, 2023

    @betatim
    Member

    @howarth would you like to open a Pull Request that implements the idea from my previous comment for RandomForest* estimators? Together with a non regression test based on your reproducer code.

  7. howarth commented on Apr 12, 2023

    @howarth
    Author

    @betatim Sure, but I won't be able to get to that for at least two weeks.

  8. added
    good first issue
    on Apr 13, 2023
  9. betatim commented on Apr 13, 2023

    @betatim
    Member

    Ok, I've marked this as a good first issue/help wanted as well. If someone else has time before @howarth, please post a message here so we can avoid duplicate work.

  10. adrinjalali commented on Apr 13, 2023

    @adrinjalali
    Member

    I don't think we want to have the feature names in all trees, as @thomasjpfan mentions, I think the fix here would be to disable validation for sub-trees instead.

  11. thomasjpfan commented on Apr 13, 2023

    @thomasjpfan
    Member

    I don't think we want to have the feature names in all trees, as @thomasjpfan mentions, I think the fix here would be to disable validation for sub-trees instead.

    This is the current behavior. The random forest disables validation when predict* runs. The opening issue is what to do if a DataFrame is passed into a sub-tree directly:

    # Trained on dataframe
    rf.fit(df, y)
    
    # Raises a warning
    rf.estimators_[0].predict_proba(df)

    If the random forest was trained on a DataFrame, then I think it is reasonable to expect the above to work without warning. This means having the feature names in all trees.

  12. adrinjalali commented on Apr 13, 2023

    @adrinjalali
    Member

    An issue I see with this approach is that it's kind of a hack. Basically, what we're doing here is to apply the mutations which _validate_data would have done to the estimator, after the fact, w/o calling _validate_data, or having passed data which is different from the data given by the user (like converted to an ndarray version of the data). And the above fix will be immediately out of date if _validate_data adds more mutations and we end up doing more checks somehow.

    So I see two clean-ish solutions here:

    • Disable input validation on the estimator level, for sub-estimators of RandomForest, so that rf.estimators_[0].predict(df) doesn't call validation and doesn't raise/warn anything.
    • Or, have a protocol where _validate_data tells us what mutations it's doing, and apply the same thing on sub-estimators.
  13. betatim commented on Apr 13, 2023

    @betatim
    Member

    Somehow the cleanest solution would be to go for a "dataframes all the way down" approach, where things are only converted as late as necessary. Compared to the current setup where conversion happens very early. This is also what #21811 (comment) proposes as a way forward. The idea of splitting check_array so that it does only checking, not checking and converting has come up a few times as well. There is also #25433 (and friends) that would also like a move in that direction.

    What was the thinking behind the current "early conversion" approach?

  14. adrinjalali commented on Apr 13, 2023

    @adrinjalali
    Member

    What was the thinking behind the current "early conversion" approach?

    1. Performance: Validation and multiple conversion can be VERY expensive. Worst case we'd have a whole data copy when converting to ndarray every time. That's also why we have things like this in the meta-estimator level:
            if issparse(X):
                # Pre-sort indices to avoid that each individual tree of the
                # ensemble sorts the indices.
                X.sort_indices()
    1. In some cases we need to know certain information about the input already in the meta-estimator level, which can be avoided in the BaseForest case it seems, but the performance reason stands. We do bootstrapping there, but we can do it w/o conversion, which probably would be more expensive too.

    So we can only delay validation when:

    1. we don't need info / modifications on the input
    2. we only fit one sub-estimator, so we won't have the issue of multiple validations
  15. betatim commented on Apr 14, 2023

    @betatim
    Member

    I could get behind the idea of turning off input validation for the sub-estimators or adding the information needed after calling fit from the parent estimator (the "hack").

    One thing I just thought about: what happens if the order of the columns changes between the df used for fit and predict? And how does this effect the current topic of passing a df to a sub-estimator that was fitted on a numpy array?

  16. wesselhuising commented on Apr 18, 2023

    @wesselhuising

    See the PR above. I pass the column names using the self.feature_names_in_ attribute of the BaseForest class and pass this list (list[str] | None) to the parallel function that instantiates all the tree's of the forest. In here the code sets the attribute feature_names_in_ to the list of the columns (in case of X being a pd.DataFrame and thus has the columns attribute).

    According this solution, the validation is still in place but the one-off extracting of the names are passed to the fitting function of every sub-estimator and only setting the attribute for that estimator. I might be missing something but I feel this will work according the dataframe all the way down and keeping validation in place.

    For the sake of testing the original example code for raising the warning: the code works fine with this extra argument into the parallel fitting function and thus does not give any warning and is able to get the original feature_names_in_ per sub-estimator.

    import numpy as np
    from sklearn.ensemble import RandomForestClassifier
    import pandas as pd
    
    if __name__ == "__main__":
        data = np.random.normal([1,2,3,4,5,6,7,8,9,10], size=(1000, 10))
        feature_names = [f'F{i}' for i in range(10)]
        df = pd.DataFrame(data=data, columns=feature_names)
        y = np.ones(1000)
        y[500:] = 0
    
        rf = RandomForestClassifier()
        rf.fit(df, y)
    
        print(f"Feature names in Forest: {rf.feature_names_in_} ")
    
        print('Classing pred proba on forest')
        rf.predict_proba(df)
        print('Done calling pred proba on forest')
    
        # THIS GIVES A WARNING
        rf.estimators_[0].predict_proba(df)
    
        print(rf.estimators_[0].predict_proba(df))
        print(rf.estimators_[0].feature_names_in_)
    
  17. vishalj0501 commented on May 12, 2023

    @vishalj0501

    Hello, I'm a first timer and new to open source contribution,
    Can I take up this issue ?

  18. brandonidas commented on May 30, 2023

    @brandonidas

    Hi, is this available to be taken?

  19. added
    Moderate
    and removed
    good first issue
    on May 30, 2023
  20. thomasjpfan commented on May 30, 2023

    @thomasjpfan
    Member

    There is already a PR opened: #26208, but we do not have an agreed solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugModeratemodule:ensemble

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions