Skip to content

Factory-style construction of composite estimators #16301

Open

Description

@jnothman

I find the API for specifying lists constituent estimators in Pipeline, FeatureUnion, ColumnTransformer, StackingClassifier, VotingClassifier, GeneralizedNB, etc. ugly. I find the make_pipeline, make_column_transformer etc interfaces helpful, but the duplication of interfaces is actually quite ugly too, and it is limiting: the moment you want to name one of your Pipeline steps explicitly, in order to make your grid search parameter space reasonably intelligible, you need to change from make_pipeline syntax to Pipeline syntax. Yuck!

I'd like to see a POC implementation and likely a SLEP towards creating a syntax like:

est = (ColumnTransformer()
       .append(CountVectorizer(), 'body_text')
       .append(KNNImputer(), ['age'], name='impute')
       .fit(X))

The append method would progressively construct the transformers parameter of est. Note that the first use of append does not give the body_text transfomer a name, so one will be automatically generated.

Note that since we delay parameter validation until fit, similar syntax is already possible:

est = (LogisticRegression()
       .set_params(penalty='l1')
       .fit(X, y))

So additional methods like append are just syntactic sugar for getting, amending and setting the steps/transformers parameter. But I think they would encourage named parameters instead of confusing tuples, creating more legible code.

Each of the above estimators would have methods similar to append or add (perhaps also insert).

PS: I have mentioned this proposal before, particularly when we ran into the inconsistent tuple ordering between make_column_transformer and ColumnTransformer.

Activity

  1. rth commented on Jul 25, 2020

    @rth
    Member

    Maybe we should mention this at the next dev meeting. I don't think many people saw this issue.

  2. NicolasHug commented on Jul 25, 2020

    @NicolasHug
    Member

    I find this interesting but I am concerned about supporting too many ways of achieving the same thing. I feel like this is what makes some libraries hard to use and learn.

    Happy to consider a SLEP though.

  3. jnothman commented on Jul 26, 2020

    @jnothman
    MemberAuthor

    I am concerned about supporting too many ways of achieving the same thing. I feel like this is what makes some libraries hard to use and learn.

    I think it is a pity we did not consider this method-based syntax before we introduced make_pipeline etc.

    The appeal of the method based approach is that it is much more explicit and self-checking: each add method has its own arguments and docstrings. The make_pipeline logic, OTOH, is completely implicit and the idea that an estimator is assigned a name automatically makes the whole thing a bit conceptually confusing.

  4. jnothman commented on Jul 26, 2020

    @jnothman
    MemberAuthor
  5. thomasjpfan commented on Jul 26, 2020

    @thomasjpfan
    Member

    The make_pipeline logic, OTOH, is completely implicit and the idea that an estimator is assigned a name automatically makes the whole thing a bit conceptually confusing.

    I would be fairly happy with using a method for creating ColumnTransformers. For me, I like append because it treats ColumnTransformer like a list.

    Side note: For 95% of the time, I use Pipeline and ColumnTransformer directly because I want to explicitly give names.

    I suspect @amueller will have a few thoughts regarding constructing DAGs and/or pipelines.

  6. jnothman commented on Jul 26, 2020

    @jnothman
    MemberAuthor
  7. GaelVaroquaux commented on Jul 27, 2020

    @GaelVaroquaux
    Member

    I think that the general idea must be explored, because we really have a need.

    I would avoid the term "append"

  8. thomasjpfan commented on Jul 27, 2020

    @thomasjpfan
    Member

    I would avoid the term "append"

    What would be a good alternative?

  9. GaelVaroquaux commented on Jul 27, 2020

    @GaelVaroquaux
    Member

    The reasons why I would avoid "append" are:

    • It's a term used in the standard objects (list) (that's not a very strong reason, but it's still confusing to have an unexpected behavior)
    • It has the notion of ordering (at least to me), and not every usage that we are considering has this notion (column transformer)

    Suggestions:

    • attach
    • assemble
    • add
    • put
    • push
  10. ogrisel commented on Jul 27, 2020

    @ogrisel
    Member

    Maybe also:

    • set

    But I think I like attach better in the context of the ColumnTransformer.

    For Pipeline: append, add or chain would be more natural because the sequential structure is important.

    I like the general idea and it's true that it's probably lead to more easy to read code, more inline with the conventions of the Deep Learning community for complex architectures and would also better interact with automated formatting tools such as black shall we use them in the future.

  11. GaelVaroquaux commented on Jul 27, 2020

    @GaelVaroquaux
    Member

    But I think I like attach better in the context of the ColumnTransformer.

    For Pipeline: append, add or chain would be more natural because the sequential structure is important.

    I think that we should use the same verb. I think that I like 'attach' too. It seems to work in many situations (Pipeline, ColumnTransformer, FeatureUnion, BaggingClassifier), and it's short.

  12. ogrisel commented on Jul 27, 2020

    @ogrisel
    Member

    Another suggestion bind (for column transformer at least).

    I am not convinced we should use the same verb for ColumnTransformer and the Pipeline: only ColumnTransformer takes the column selector as (primary) argument for this builder method.

  13. NicolasHug commented on Jul 27, 2020

    @NicolasHug
    Member

    pipe?

  14. GaelVaroquaux commented on Jul 27, 2020

    @GaelVaroquaux
    Member
  15. justmarkham commented on Jul 27, 2020

    @justmarkham
    Contributor

    I wanted to get a feel for how some of my teaching code would look under this proposal, so I created some examples. I started with Pipeline, since it's a bit easier to digest:

    Pipeline

    # option 1
    pipe = make_pipeline(ct, logreg)
    
    # option 2
    pipe = Pipeline([('preprocessor', ct), ('classifier', logreg)])
    
    # option 3 (proposed)
    pipe = Pipeline().append(ct).append(logreg)
    
    # option 4 (proposed)
    pipe = (Pipeline()
           .append(ct, name='preprocessor')
           .append(logreg, name='classifier'))

    Option 1: This is what I use 95% of the time. It's easy to read and write, I know exactly what's in it (because of my own naming conventions), and I know exactly what the assigned step names will be.

    Option 2: I don't like that I am required to name all of the steps, and I especially don't like writing or reading ([( and )]) at the start and end of every Pipeline. It's too easy to make mistakes.

    Option 3 (no step names): I still prefer option 1, but option 3 is okay. I could get used to it.

    Option 4 (step names): I like that the step names come after the objects and that the step names are optional. I don't particularly like wrapping the entire thing in parentheses. I'm not sure if I prefer option 2 or option 4.

    ColumnTransformer

    # option 1
    ct = make_column_transformer(
        (imp_ohe, ['Embarked', 'Sex']),
        (vect, 'Name'),
        (imp, ['Age', 'Fare']),
        ('passthrough', ['Parch']))
    
    # option 2
    ct = ColumnTransformer(
        [('imp_ohe', imp_ohe, ['Embarked', 'Sex']),
         ('vect', vect, 'Name'),
         ('imp', imp, ['Age', 'Fare']),
         ('pass', 'passthrough', ['Parch'])])
    
    # option 3 (proposed)
    ct = (ColumnTransformer()
          .append(imp_ohe, ['Embarked', 'Sex'])
          .append(vect, 'Name')
          .append(imp, ['Age', 'Fare'])
          .append('passthrough', ['Parch']))
    
    # option 4 (proposed)
    ct = (ColumnTransformer()
          .append(imp_ohe, ['Embarked', 'Sex'], name='imp_ohe')
          .append(vect, 'Name', name='vect')
          .append(imp, ['Age', 'Fare'], name='imp')
          .append('passthrough', ['Parch'], name='pass'))

    Option 1: This is what I use 95% of the time. It's somewhat easy to make mistakes because of the number of commas and parentheses, but I've gotten used to it.

    Option 2: I don't like that I am required to name all of the transformers. I find it hard to write because of the number of parentheses, commas, and brackets.

    Option 3 (no transformer names): I'm okay with this. I may still have a slight preference for option 1.

    Option 4 (transformer names): I like this a bit better than option 2, especially because the transformer names are optional.

    Overall assessment

    I think the case for this proposal is stronger for ColumnTransformer than for Pipeline.

    I share @NicolasHug's concern of having three different ways to do the same thing. So much code is already out "in the wild" that uses the existing two options that even if we strongly recommended the new way, it's fair to assume that the existing two options will continue to be used for many years to come. That may make things especially tough for new users.

    Assuming this proposal was accepted, it's not clear to me whether deprecating make_pipeline and make_column_transformer would make things better or worse.

    Method naming

    I like the idea of having one method name that is used with all composite estimators, since that is less for the user to remember.

    At the moment, I like add the best because:

    • It feels the most natural: "Add this to your Pipeline" and "add this to your ColumnTransformer" both sound natural.
    • It's short: It's fast to type, and it doesn't overwhelm your eyes when reading it.
    • It doesn't imply an ordering: I wouldn't want to use a method name for ColumnTransformer that implies an ordering. Getting students to understand the difference between Pipeline and ColumnTransformer is already quite difficult, and I believe a method name like "append" would make that harder.
  16. thomasjpfan commented on Jul 27, 2020

    @thomasjpfan
    Member

    As a reference, users coming from keras would be familiar with the following:

    model = keras.Sequential(
        [
            layers.Dense(2, activation="relu", name="layer1"),
            layers.Dense(3, activation="relu", name="layer2"),
            layers.Dense(4, name="layer3"),
        ]
    )

    or

    model = keras.Sequential(name="my_sequential")
    model.add(layers.Dense(2, activation="relu", name="layer1"))
    model.add(layers.Dense(3, activation="relu", name="layer2"))
    model.add(layers.Dense(4, name="layer3"))
  17. GaelVaroquaux commented on Jul 27, 2020

    @GaelVaroquaux
    Member

    As I mentioned in the call, we can now use dicts (and hence kwargs) which are ordered. The following synthax would be possible:

    make_pipeline(ohe=ohe, log_reg=log_reg)
    
    ct = make_column_transformer(
        imp_ohe=(imp_ohe, ['Embarked', 'Sex']),
        vect=(vect, 'Name'),
        imp=(imp, ['Age', 'Fare']),
        other=('passthrough', ['Parch'])
    )
    

    doesn't fully remove the clunckiness :)

  18. jnothman commented on Jul 27, 2020

    @jnothman
    MemberAuthor
  19. jnothman commented on Jul 27, 2020

    @jnothman
    MemberAuthor

    Thanks for your feedback @justmarkham.

    I'm not sure that your comparison is entirely fair, since if

    pipe = make_pipeline(ct, logreg)
    

    is sufficient, then so is:

    pipe = Pipeline().add(ct).add(logreg)
    

    In some ways this is poorer to read, but it is simpler in the sense that:

    • you always import Pipeline, and don't need to decide if Pipeline or make_pipeline is a better choice. (We could have facilitated that by making make_pipeline instead a classmethod Pipeline.make.)
    • it is easy to change one or both steps to having explicit names later.
  20. adrinjalali commented on Jul 28, 2021

    @adrinjalali
    Member

    It's been a year. I'd be very happy if we revive this. Tagging @scikit-learn/core-devs since it's also related to some of the efforts related to the sample props SLEP (SLEP006).

    Seems like there's a [at least weak] consensus on a way forward.

  21. lorentzenchr commented on Jul 28, 2021

    @lorentzenchr
    Member

    I’d like the idea of an add method, but have the same concern as @NicolasHug #16301 (comment).
    If we add something new, do we also want to get rid of something old?

  22. jnothman commented on Jul 29, 2021

    @jnothman
    MemberAuthor

    I find this interesting but I am concerned about supporting too many ways of achieving the same thing. I feel like this is what makes some libraries hard to use and learn.

    That's a good point... I think that if we add a "better" API, we should change the examples/tutorial to use it. Where a method is added to control a parameter, we should note in the parameter docstring that the method is preferred. This specific proposal might involve deprecating make_pipeline etc which are convenient, but add some obscurity.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions