Repository navigation
Description
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 tagsFor 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 != FalseWithout 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
NicolasHug commentedon Jun 8, 2019
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))
glemaitre commentedon Jun 8, 2019
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)
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.
NicolasHug commentedon Jun 10, 2019
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)versusMyClass(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.
rth commentedon Jun 11, 2019
Indeed. But currently, this doesn't work,
while there is no ambiguity here, the estimator should be able to overwrite its tags no matter their values in base classes.
amueller commentedon Jun 11, 2019
@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, becausesuperinBaseEstimatorwill returnBaseMixin, right?Example:
produces
So BranchB gets resolved before BranchA, and then BranchA gets the result from BranchB.
This would theoretically work if we changed the order of
BaseEstimatorandMixinin all of our class constructions. Basically withsuperwe 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.
amueller commentedon Jun 11, 2019
See the left vs right discussion here:
#8022 (comment)
So the actual bugfix is putting mixins on the left, as Python does it.
glemaitre commentedon Jun 11, 2019
If we let the issue with the MRO and
super()aside, could we allowBottomto 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:scikit-learn/sklearn/base.py
Line 323 in 9d7b804
rth commentedon Jun 11, 2019
@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
that wouldn't work? This wouldn't have to deal with all that MRO topic I think?
glemaitre commentedon Jun 11, 2019
This is the issue illustrated in #14044 (comment)
amueller commentedon Jun 11, 2019
Ah, ok. I think we
cancould 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.
NicolasHug commentedon Jun 11, 2019
I don't think that would work either @rth, since there might be inconsistencies higher in the class inheritance (here)
rth commentedon Jun 11, 2019
At least in my example above the exception happens later L323 not L319, so it should be fine.
Ahh, indeed that is a problem, hmm.
rth commentedon Jun 11, 2019
There was a hack in #8022 (comment) proposing to order tag inheritence by
Mixin,BaseClasses,BaseEstimatorfirst, and MRO second, but noone liked it :)4 remaining items
NicolasHug commentedon Jun 11, 2019
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.
amueller commentedon Jun 11, 2019
The mixin on the left will win.
NicolasHug commentedon Jun 11, 2019
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.
amueller commentedon Jun 20, 2019
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?
amueller commentedon Aug 12, 2019
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.
glemaitre commentedon Aug 12, 2019
You should blame @agramfort apparently :)
495fb3a
amueller commentedon Aug 12, 2019
@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.
GaelVaroquaux commentedon Aug 12, 2019
amueller commentedon Aug 13, 2019
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.
amueller commentedon Aug 13, 2019
@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
supereven though they don't inherit from the base-class.rth commentedon Aug 22, 2019
I agree that using
class Estimator(ClassifierMixin, BaseEstimator)orclass Estimator(BaseClassifier)whereBaseClassifier(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)withclass BaseClusterTransformer(TransformerMixin, BaseCluster)seems not ideal.Similarly there are classes like
OrthogonalMatchingPursuit(LinearModel, RegressorMixin, MultiOutputMixin). How would they be defined without mixins?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.
amueller commentedon Sep 4, 2019
fixed by #14884
amueller commentedon Sep 4, 2019
@rth to answer your question
No, our wrong order of mixins prevents us from using
super, and I don't think it's a good idea.amueller commentedon Sep 5, 2019
The original issue is fixed in #14884, but I am tempted to open another issue to discuss mixins vs base classes.