You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
RandomForest not passing feature names to trees and creating warnings. #26140
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
importnumpyasnpfromsklearn.ensembleimportRandomForestClassifierprint(sklearn.__version__)
data=np.random.normal([1,2,3,4,5,6,7,8,9,10], size=(1000, 10))
feature_names= [f'F{i}'foriinrange(10)]
df=pd.DataFrame(data=data, columns=feature_names)
y=np.ones(1000)
y[500:] =0rf=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 WARNINGrf.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(
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.
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 ;)
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).
@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.
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.
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.
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 dataframerf.fit(df, y)
# Raises a warningrf.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.
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.
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?
What was the thinking behind the current "early conversion" approach?
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:
ifissparse(X):
# Pre-sort indices to avoid that each individual tree of the# ensemble sorts the indices.X.sort_indices()
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:
we don't need info / modifications on the input
we only fit one sub-estimator, so we won't have the issue of multiple validations
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?
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_)
Activity
betatim commentedon Apr 11, 2023
Thanks for reporting this. What happens is that the
dfyou 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 thedfit 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.
betatim commentedon Apr 11, 2023
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:I was expecting this to lead to a warning when the estimators are used from
rf.predict_probabut 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 ;)
thomasjpfan commentedon Apr 11, 2023
As mentioned in #26140 (comment),
RandomForest*is configured to not validate inpredict, so we can get away with setting the feature names directly. I'm okay with adjustingRandomForest*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).betatim commentedon Apr 12, 2023
@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.howarth commentedon Apr 12, 2023
@betatim Sure, but I won't be able to get to that for at least two weeks.
betatim commentedon Apr 13, 2023
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.
adrinjalali commentedon Apr 13, 2023
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.
thomasjpfan commentedon Apr 13, 2023
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: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.
adrinjalali commentedon Apr 13, 2023
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_datawould 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_dataadds more mutations and we end up doing more checks somehow.So I see two clean-ish solutions here:
RandomForest, so thatrf.estimators_[0].predict(df)doesn't call validation and doesn't raise/warn anything._validate_datatells us what mutations it's doing, and apply the same thing on sub-estimators.betatim commentedon Apr 13, 2023
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_arrayso 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?
adrinjalali commentedon Apr 13, 2023
BaseForestcase 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:
betatim commentedon Apr 14, 2023
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
dfused forfitandpredict? And how does this effect the current topic of passing adfto a sub-estimator that was fitted on a numpy array?wesselhuising commentedon Apr 18, 2023
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 attributefeature_names_in_to the list of the columns (in case of X being apd.DataFrameand thus has thecolumnsattribute).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.vishalj0501 commentedon May 12, 2023
Hello, I'm a first timer and new to open source contribution,
Can I take up this issue ?
brandonidas commentedon May 30, 2023
Hi, is this available to be taken?
thomasjpfan commentedon May 30, 2023
There is already a PR opened: #26208, but we do not have an agreed solution.