Skip to content

Estimator tag overwriting and update in _get_tags #14044

Closed

Description

@glemaitre

I am updating some code in imbalanced-learn to use the estimator tag. In some way, I was able to add a new entry in the _DEFAULT_TAGS and use the implementation of _safe_tags.

I have the following use case:

_DEFAULT_TAGS = {'sample_indices': False}

class BaseClass:
    ...
    def _more_tags(self):
        return {'sample_indices': True}

class SpecialClass(BaseClass):
    ...
    def _more_tags(self):
        tags = super()._more_tags()
        tags['sample_indices'] = False
        return tags

For some reason, all estimators inheriting from the BaseClass would have a sample_indices tag to True. All but not for one class where I would like to overwrite the tag. Here, I made use of the super class to give the trick that I think could solve the following issue.

Because we are overwriting the sample_indices, _get_tag is failing due to what is currently considered as an inconsistent update of the tags dictionary:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-5558b1aebfa8> in <module>
----> 1 _safe_tags(xx, 'sample_indices')

~/Documents/packages/scikit-learn/sklearn/utils/estimator_checks.py in _safe_tags(estimator, key)
     68     if hasattr(estimator, "_get_tags"):
     69         if key is not None:
---> 70             return estimator._get_tags().get(key, _DEFAULT_TAGS[key])
     71         tags = estimator._get_tags()
     72         return {key: tags.get(key, _DEFAULT_TAGS[key])

~/Documents/packages/scikit-learn/sklearn/base.py in _get_tags(self)
    320         if hasattr(self, '_more_tags'):
    321             more_tags = self._more_tags()
--> 322             collected_tags = _update_if_consistent(collected_tags, more_tags)
    323         tags = _DEFAULT_TAGS.copy()
    324         tags.update(collected_tags)

~/Documents/packages/scikit-learn/sklearn/base.py in _update_if_consistent(dict1, dict2)
    132         if dict1[key] != dict2[key]:
    133             raise TypeError("Inconsistent values for tag {}: {} != {}".format(
--> 134                 key, dict1[key], dict2[key]
    135             ))
    136     dict1.update(dict2)

TypeError: Inconsistent values for tag sample_indices: True != False

Without the call of super(), I find this rule quite meaningful and the error raising a good thing. However, I think that we could lift this rule in case where we call super() in self._more_tag. By calling super(), one should be aware of overwriting the base-class default tag.

Thus, by introspecting self._more_tag and check that super() is called (e.g. using 'super' in inspect.getclosurevars(self._more_tags).builtins), we could still allow to update the tags.

@amueller @rth @jnothman Do you think that it is use case and a solution which make sense. I still have the option to add a _more_tag to each classes but this is a lot of duplicated code then.

So the changes would be something like the following:

-def _update_if_consistent(dict1, dict2):
+def _update_if_consistent(dict1, dict2, force=False):
     common_keys = set(dict1.keys()).intersection(dict2.keys())
-    for key in common_keys:
-        if dict1[key] != dict2[key]:
-            raise TypeError("Inconsistent values for tag {}: {} != {}".format(
-                key, dict1[key], dict2[key]
-            ))
+    if not force:
+        for key in common_keys:
+            if dict1[key] != dict2[key]:
+                raise TypeError("Inconsistent values for tag {}: {} != {}"
+                                .format(key, dict1[key], dict2[key]))
     dict1.update(dict2)
     return dict1
 
@@ -319,7 +319,10 @@ class BaseEstimator:
                                                        more_tags)
         if hasattr(self, '_more_tags'):
             more_tags = self._more_tags()
-            collected_tags = _update_if_consistent(collected_tags, more_tags)
+            force = 'super' in inspect.getclosurevars(self._more_tags).builtins
+            collected_tags = _update_if_consistent(
+                collected_tags, more_tags, force=force
+            )
         tags = _DEFAULT_TAGS.copy()
         tags.update(collected_tags)
         return tags

Activity

  1. NicolasHug commented on Jun 8, 2019

    @NicolasHug
    Member

    I still have the option to add a _more_tag to each classes

    I don't think that would work. _get_tags() only allows the default tags (declared in base.py) to be overridden once in the class hierarchy.

    I don't remember why this was decided in the first place but @amueller might have more insight.

    May I ask what you plan to use the 'sample_indices' tag for? Using tags for anything else than estimator checks is prone to many issues (#13565 (comment))

  2. glemaitre commented on Jun 8, 2019

    @glemaitre
    MemberAuthor

    I don't think that would work. _get_tags() only allows the default tags (declared in base.py) to be overridden once in the class hierarchy.

    I was maybe not precise enough. When I meant each class, I meant each specialized class. This would work (cf. https://github.com/scikit-learn-contrib/imbalanced-learn/pull/577/files)

    May I ask what you plan to use the 'sample_indices' tag for? Using tags for anything else than estimator checks is prone to many issues (#13565 (comment))

    This is actually the case. We want to use it for enabling a common test in our estimator checks for the sampler which complement the one of scikit-learn.

  3. NicolasHug commented on Jun 10, 2019

    @NicolasHug
    Member

    Ok thanks.

    IIRC it was decided not to rely on super() for _get_tags() because it would make the MRO (and thus the tags of an instance) dependent on the order of the base classes, e.g. MyClass(BaseClasse1, BaseClasse2) versus MyClass(BaseClass2, BaseClass1).

    So I don't think we want to introduce super() again.


    But I agree the current design is quite rigid.

    As far as I understand, the main constraint we need to enforce for tag resolution is that classes that are direct parents of a subclass need to agree on their tags, unless this subclass overrides them.

    That is, for all tags that D does not override, B and C need to agree.

                              B       C
                               \      /
                                \    /
                                 \  /
                                  D
    
  4. rth commented on Jun 11, 2019

    @rth
    Member

    As far as I understand, the main constraint we need to enforce for tag resolution is that classes that are direct parents of a subclass need to agree on their tags, unless this subclass overrides them.

    Indeed. But currently, this doesn't work,

    >>> from sklearn.base import BaseEstimator
    >>> class BaseMixin:
    ...     def _more_tags(self):
    ...         return {'new_tag': 23}
    ... 
    >>> class MyEstimator(BaseEstimator, BaseMixin):
    ...     def _more_tags(self):
    ...         return {'new_tag': 0}
    ... 
    >>> MyEstimator()._get_tags()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/rth/src/scikit-learn/sklearn/base.py", line 323, in _get_tags
        collected_tags = _update_if_consistent(collected_tags, more_tags)
      File "/home/rth/src/scikit-learn/sklearn/base.py", line 135, in _update_if_consistent
        key, dict1[key], dict2[key]
    TypeError: Inconsistent values for tag new_tag: 23 != 0

    while there is no ambiguity here, the estimator should be able to overwrite its tags no matter their values in base classes.

  5. amueller commented on Jun 11, 2019

    @amueller
    Member

    @rth if you can find a way to actually do this reasonably, cool.
    I could not come up with a better design. I wouldn't consider this a bug, though it is rigid.
    as @NicolasHug says, if you allow that the value of the tags depends on the MRO. I don't like relying on the value of the MRO.
    You're saying there is no ambiguity here because BaseEstimator has no new_tag?

    You can't implement this with super, though, I think, because super in BaseEstimator will return BaseMixin, right?

    Example:

            
    class BranchA():
        def f(self):
            s = super()
            current_tags = set()
            if hasattr(s, 'f'):
                current_tags.update(super().f())
            print("In BranchA from super")
            print(current_tags)
            current_tags.update({'BranchA'})
            print("In BranchA after adding")
            print(current_tags)
            return current_tags
            
    class BranchB():
        def f(self):
            s = super()
            current_tags = set()
            if hasattr(s, 'f'):
                current_tags.update(super().f())
            print("In BranchB from super")
            print(current_tags)
            current_tags.update({'BranchB'})
            print("In BranchB after adding")
            print(current_tags)
            return current_tags
    
    class Bottom(BranchA, BranchB):
        def f(self):
            s = super()
            current_tags = set()
            if hasattr(s, 'f'):
                current_tags.update(super().f())
            print("In Bottom from super")
            print(current_tags)
            current_tags.update({'Bottom'})
            print("In Bottom after adding")
            print(current_tags)
            return current_tags

    produces

    In BranchB from super
    set()
    In BranchB after adding
    {'BranchB'}
    In BranchA from super
    {'BranchB'}
    In BranchA after adding
    {'BranchB', 'BranchA'}
    In Bottom from super
    {'BranchB', 'BranchA'}
    In Bottom after adding
    {'BranchB', 'BranchA', 'Bottom'}
    

    So BranchB gets resolved before BranchA, and then BranchA gets the result from BranchB.

    This would theoretically work if we changed the order of BaseEstimator and Mixin in all of our class constructions. Basically with super we can have the thing on the left overwrite the tags from the right, but we can't have the thing on the right overwrite the thing from the left.

    We could theoretically forgo using the MRO and construct the actual inheritance graph and see if we an disambiguate. But that's really not how inheritance is supposed to work.

  6. amueller commented on Jun 11, 2019

    @amueller
    Member

    See the left vs right discussion here:
    #8022 (comment)

    So the actual bugfix is putting mixins on the left, as Python does it.

  7. glemaitre commented on Jun 11, 2019

    @glemaitre
    MemberAuthor

    If we let the issue with the MRO and super() aside, could we allow Bottom to overwrite tags? I see the point of the consistency between base classes. However, I don't see why we could not just update the tags there:

    collected_tags = _update_if_consistent(collected_tags, more_tags)

  8. rth commented on Jun 11, 2019

    @rth
    Member

    @amueller I might indeed be missing something, my recollection of this PR is somewhat blurry. So you are saying that, if here you always update the tags e.g. something like

    - collected_tags = _update_if_consistent(collected_tags, more_tags)
    + collected_tags = _update_if_consistent(collected_tags, more_tags, check_consistency=False)

    that wouldn't work? This wouldn't have to deal with all that MRO topic I think?

  9. glemaitre commented on Jun 11, 2019

    @glemaitre
    MemberAuthor

    This is the issue illustrated in #14044 (comment)

  10. amueller commented on Jun 11, 2019

    @amueller
    Member

    Ah, ok. I think we can could remove that check.

    However, as soon as anything inherits from this estimator, the inheriting estimator will break. I think I wanted to avoid making inheriting from an estimator invalid, because that's a really weird thing to do.

  11. NicolasHug commented on Jun 11, 2019

    @NicolasHug
    Member

    I don't think that would work either @rth, since there might be inconsistencies higher in the class inheritance (here)

  12. rth commented on Jun 11, 2019

    @rth
    Member

    I don't think that would work either rth, since there might be inconsistencies higher in the class inheritance (here L319)

    At least in my example above the exception happens later L323 not L319, so it should be fine.

    However, as soon as anything inherits from this estimator, the inheriting estimator will break. I think I wanted to avoid making inheriting from an estimator invalid, because that's a really weird thing to do.

    Ahh, indeed that is a problem, hmm.

  13. rth commented on Jun 11, 2019

    @rth
    Member

    We could theoretically forgo using the MRO and construct the actual inheritance graph and see if we an disambiguate.

    There was a hack in #8022 (comment) proposing to order tag inheritence by Mixin, BaseClasses, BaseEstimator first, and MRO second, but noone liked it :)

  14. 4 remaining items

  15. NicolasHug commented on Jun 11, 2019

    @NicolasHug
    Member

    I don't see how changing the order of the mixins will solve the issue in general: what if 2 mixins disagree on a tag?

    I've opened #14069 that implements #14044 (comment) if you wanna take a look.

  16. amueller commented on Jun 11, 2019

    @amueller
    Member

    The mixin on the left will win.

  17. NicolasHug commented on Jun 11, 2019

    @NicolasHug
    Member

    Right, so what if you want some other attribute (other than tags) to be inherited from another mixin (that is not the left-most one)?

    I thought the whole point was to not rely on the MRO for the tags.

  18. amueller commented on Jun 20, 2019

    @amueller
    Member

    The point was that it was impossible to rely on the MRO in a sensible way. Ideally I would not have anything rely on the MRO but I think redefining inheritance is even worse.

    I'm not sure I understand your example. If they define different tags and different implementations of the same method there is no way for you to select one from one and the other from the other, right?

  19. amueller commented on Aug 12, 2019

    @amueller
    Member

    Ok I think I'll try to fix this by actually getting rid of mixins. I think our current class hierarchy is kinda silly.
    @GaelVaroquaux maybe you have time at some point to explain to me why we have mixins instead of using inheritance, and why we put the mixins to the right.

  20. glemaitre commented on Aug 12, 2019

    @glemaitre
    MemberAuthor

    we have mixins instead of using inheritance

    You should blame @agramfort apparently :)

    495fb3a

  21. amueller commented on Aug 12, 2019

    @amueller
    Member

    @agramfort, explain yourself! ;)
    For now, I have a fix that doesn't entirely kill the mixin idea but introduces a class above everything in the hierarchy: #14635

    I would probably prefer undoing 495fb3a and making the mixins ABCs. But the solution works as-is, I think.

  22. GaelVaroquaux commented on Aug 12, 2019

    @GaelVaroquaux
    Member
  23. amueller commented on Aug 13, 2019

    @amueller
    Member

    I don't understand your argument @GaelVaroquaux. Mixins are a form of multiple inheritance. Therefore saying "mixins are more flexible than inheritance" makes no sense to me.

  24. amueller commented on Aug 13, 2019

    @amueller
    Member

    @GaelVaroquaux more concretely, the difference to me is that Mixins are feature add-ons that are not instances of the base class.
    There is our tag mechanism rewritten, once by fixing our (currently wrong) Mixin architecture: #14644 and once using a base class: #14635

    Both use inheritance, but I would argue the one that uses a base-class (which imho should just be BaseEstimator) is much clearer.
    In particular, in the other one, the mixins call super even though they don't inherit from the base-class.

  25. rth commented on Aug 22, 2019

    @rth
    Member

    Both use inheritance, but I would argue the one that uses a base-class (which imho should just be BaseEstimator) is much clearer.

    I agree that using class Estimator(ClassifierMixin, BaseEstimator) or class Estimator(BaseClassifier) where BaseClassifier(ClassifierMixin, BaseEstimator) should be pretty much equivalent.

    The complication comes with multiple inheritence. Without mixins how would you write class Birch(TransformerMixin, ClusterMixin, BaseEstimator)?

    • class Birch(TransformerMixin, BaseCluster) is still using mixins.
    • class Birch(BaseClusterTransformer) with class BaseClusterTransformer(TransformerMixin, BaseCluster) seems not ideal.

    Similarly there are classes like OrthogonalMatchingPursuit(LinearModel, RegressorMixin, MultiOutputMixin). How would they be defined without mixins?

    In particular, in the other one, the mixins call super even though they don't inherit from the base-class.

    I quickly checked -- I don't think that any of the existing mixin do (except for the proposal in #14644). So it's more that mixins prevents us from using super there, which IMO is a good thing in the case of multiple inheritance.

  26. amueller commented on Sep 4, 2019

    @amueller
    Member

    fixed by #14884

  27. amueller commented on Sep 4, 2019

    @amueller
    Member

    @rth to answer your question

    class Birch(BaseTransformer, BaseCluster):
       ...
    
    class OrthogonalMatchingPursuit(BaseLinearRegressor, BaseMultiOutput):
       ...

    So it's more that mixins prevents us from using super there, which IMO is a good thing in the case of multiple inheritance.

    No, our wrong order of mixins prevents us from using super, and I don't think it's a good idea.

  28. amueller commented on Sep 5, 2019

    @amueller
    Member

    The original issue is fixed in #14884, but I am tempted to open another issue to discuss mixins vs base classes.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions