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
RFC switch to Polars as the default dataframe lib in our examples #28341
We now support polars as an output for our transformers and ColumnTransformer, but our examples use pd.DataFrame.
Our datasets module also returnes either a numpy array or a pandas DataFrame.
I'm suggesting that we enable datasets to return a polars dataframe, and to switch our examples from pandas to polars.
This has a few benefits:
Polars on users' systems takes advantage of multi-core CPUs which is the case for pretty much all users these days. So it's quite faster in most cases.
Pandas is dealing with issues related to Arrow, and even if they don't require Arrow as a required dependency, there will be behavior changes whether Arrow is installed or not at least on String Dtype.
Another thing is the (in)stability issues related to Pandas API where we need to deal with deprecation warnings very often. Although I'm not sure how stable the API is on the places where we touch the API on the polars side (maybe cc @MarcoGorelli )
This is not really a core part of our library, but what we put in our examples and our default choices affect people since many learn from our examples.
Reacted by Julien Jerphanion, Stijn de Gooijer, Juan Luis Cano Rodríguez, Samay Kapadia, taozuoqiao, Dustin Ballentine, Nicolo Ceneda, Richard Höchenberger, Ceyda Cinarel (재이다), Kunal Mishra and 2 more
Reacted by Marco Edward Gorelli, Thijs Nieuwdorp, Jeroen Janssens, Stijn de Gooijer, Ion Koutsouris, Ritchie Vink, Julian, baggiponte, Juan Luis Cano Rodríguez, Ferdinand Köppen and 4 more
I'm suggesting that we enable datasets to return a polars dataframe, and to switch our examples from pandas to polars.
While I love polars, I think that most users still use pandas. I thus would argue to have both in the examples. By both, I do not mean double the work, but switch a few, keep a few in pandas, and each time mention in a comment that scikit-learn works with both.
I agree with @GaelVaroquaux. I would be considering having a mix of example, even more when we don't take profit from polars features.
Currently our support for polars is closer to rewrapping a NumPy arrays into a Polars DataFrame without leveraging the lazyness.
In an ideal world, if we come to have estimator to leverage those features (e.g. via the dataframe API) then we should certainly demonstrate it in the documentation.
Although I'm not sure how stable the API is on the places where we touch the API on the polars side
As far as I can tell, internally you're just using __dataframe__ (the dataframe interchange protocol) and __array__:
__dataframe__: this is implemented natively without relying on pyarrow (thanks to a lot of work by the incredible @stinodego), and its API should be stable. Even if there's any internal change in Polars, the public API in __dataframe__ shouldn't change (that's one good thing about standards!)
__array__: for numeric and string datatypes, pyarrow isn't required (though it is required for Categorical). Pretty sure this one can be considered stable anyway
In an ideal world, if we come to have estimator to leverage those features (e.g. via the dataframe API)
I've been having a hard time convincing the relevant people that those (lazy) features are a "must-have", so no promises that this will be possible I'm afraid. Input on data-apis/dataframe-api#346 would be appreciated (whether you agree, or whether I've misunderstood and am wrong)
Panda's block manager that supports 2D arrays is still nicer memory-wise when it comes to the roundtrip: numpy -> dataframe -> numpy. Pandas can hold on to numerical F-contiguous or C-contiguous NumPy array underneath the covers. This allows us to use Panda's dataframes in a scikit-learn Pipeline without introducing memory overhead.
I do not think polars is as a point where it can do the roundtrip without making a copy, which increasess memory usage. Because of this memory issue, I would still recommend converting polars dataframes to pandas before handing it over to scikit-learn's Pipeline.
With the memory issue in polars, I do not think we are in a good state to promote it's usage. I see two options to improve the situation around polars:
polars stores 2d NumPy arrays without converting it into a columnar format
scikit-learn becomes "dataframe first" and run operations directly on dataframes
We can make use of lazy dataframes in this case.
Not all algorithms are suitable for columnar data. (anything with matmul we need to be rethought)
I was mentioning the same memory issue, but @thomasjpfan already did that better just now
Pandas is dealing with issues related to Arrow, and even if they don't require Arrow as a required dependency, there will be behavior changes whether Arrow is installed or not at least on String Dtype.
FWIW I don't expect any behaviour changes for the string dtype (you could also already test that with the latest pandas, which reminds me I should do a scikit-learn test run with pandas Copy-on-Write enabled). When converting to numpy, this still becomes object dtype, and I assume that's mostly the way that scikit-learn encounters it eventually.
(and nitpick: it's PyArrow, not "Arrow" in general, there are many Arrow implementations, including one embedded in polars ;))
I should do a scikit-learn test run with pandas Copy-on-Write enabled
FYI I did a quick and dirty attempt #27879 (comment). The preliminary result is that there are 2 failures but some of the issues may not be caught by our tests e.g. the one reported in #27879.
I did an experiment using only Polars (not even Numpy) for my ML pipelines during 2022-2023. I rewrote almost all Transformers and metrics using Polars + some Rust. Let me share my two cents on this issue:
Pros:
(1) You get the speed gain trivially. But this is not the most important factor.
(2) It is so much easier to write for Polars and Polars alone. (Polars in, Polars out)
Why? Because Polars enforces a strict type system. Polars has methods that internally handles null values, which makes Polars so much better than NumPy in practice. Imputation and scaling become trivial. No need to tons of if isinstance(...) and unnecessary branches. Once you start dealing with multiple output types, life gets harder..
(3) A lot more stuff can be written as Polars queries (heck even in SQL queries). ROC AUC can be computed as a SQL query and thus can be translated to Polars, and you can see the speed gain. Target encoding again can be computed as a SQL query and therefore can be rewritten in Polars... Thus using Polars, we can safely say goodbye to category_encoders.
(4) A transformer, in essence, is a function that outputs a recipe on how to replicate a mapping for some columns in the dataframe. As long as this recipe can be pickled, the same transform will work for training and testing, and all data splits. This is where Polars expressions come in. Almost all Polars's native expressions are pickle-able, so they can be reused. (I have not tested Polars plugin expression). This makes feature engineering again trivial in Polars.
Setting up a custom transfomer is a pain in current Sklearn because function transformers cannot be pickled properly. But say you want to do LogTransform. Do you really need all that inherited class nonsense? In polars you just do pl.col("a").log() and here you go this is your transformer. We run into this issue a lot in practice, where in our dataset we have feature A and B, but we need to use feature A/B. What we do now is to go back to SQL and add this feature. But during deployment, this adds work for Dev and sometimes the engineered feature gets complicated. Using Polars we can leave the SQL as it is. Pull only the raw feature set and keep feature engineering in Python in a VERY CLEAN way and everything is pickle-able and reusable so life is good. Using Transformer for this is not as clean, and for each project, the reusability of these transformers are suspicious. So I think expressions are superior in this case. We can therefore safely say goodbye to dependencies like Scikit-lego, feature-engine, or whatever feature engineering library that claims to be compatible with sklearn..
Cons:
(1) Backwards compatibility. Obviously a lot of things will need to be rewritten in Polars. This is not a con to me, but is a con to Sklearn the package.
(2) It might be harder to debug when running lazy polars. Because Lazy Polars won't stop at the exact point in the query to tell you what is wrong. Rather, it tells you what is wrong without telling you where exactly is the problem. That said, debugging in current sklearn can also be hard if you are using the BaseTransformers and other low-level classes.
I cannot really think of anything else.
Other comments:
(1) From my experience, for those who are doing traditional ML, the speed gain pointed out above does not matter so much. It's like 5s to 1s. Nothing critical unless you are serving stuff in real time, which is rare.
(2) I am the author of a package called polars-ds. If you are interested in doing data science with Polars and Rust, and like working with dataframe queries, then please check it out!
call .to_pandas() before passing to a scikit-learn Pipeline
There are two types of examples:
If the preprocessing in polar does not have state, then that is a simple example.
If preprocessing has state which is learned during fit and used during transform, then the example is to wrap the Polars expressions into a scikit-learn transformer.
@abstractqqq scikit-learn's transformers is mostly about keeping track of state between fit and transform. For example:
We can write a Polars expression to do SimpleScalar, but it'll need some state object to hold on to the mean and std during fit time. In this case, the state object can easily be another Polars DataFrame. During transform, there needs to be another Polars expression that takes the mean and std and uses it on new data. (During transform time, we do not need to compute the mean anymore).
For imputers, we need to store a statistic for the training data and use it to impute the test data.
Due to the constraints of scikit-learn, I think it's better to look into Polars for ML in a separate project as you have done with polars-ds. There is a good subset of ML techniques and algorithms that can make use of Polar's plugin system, and it is worth exploring.
@thomasjpfan You are exactly right it is about keeping the states. But I think it boils down to two steps: (1) learn from train. We can learn the mean, std, from a Polars df, and this is multithreaded by default in Polars. (2) we can then pass these learned knowledge into expressions in Polars. E.g pl.col("a").fill_null(learned_value). Now this is a perfectly valid way of preserving states. Once we have a list of such expressions, we transform each at once, which again will be in parallel in Polars by default
Whatever the conclusions, this peeks my interest. ^^
Let's make clear what we can do on the Polars side.
Zero copy from a 2D numpy matrix to a Polars DataFrame is possible in depending on the row-order. We can memory map the columns.
Zero copy from a Polars DataFrame to to numpy matrix will not be possible. However, we heavily parallelized the copy, and don't expect it to be the bottleneck. I expect there are quite some implicit copies in a current implementations.
1D columnar (without nulls) will be completely zero-copy in both directions.
2D numpy matrix (without nulls) will be completely zero-copy to the Polars Array data-type and back.
We will implement the numpy array interface very soon and that will follow the above rules on (zero)-copyness.
Reacted by Andreas Mueller, stonebig, nirvana-msu and Max Bronckers
Reacted by Thijs Nieuwdorp, Meekail Zain, Alexander Beedie, Darek and Max Bronckers
So it seems a [to be confirmed with benchmarks] summary of this thread is:
pre/post sklearn steps might be / most probably are quite faster on polars
in between sklearn.Pipeline steps pandas might be faster, due to lack of memory copies.
I'm not sure, and I would need to see benchmarks to confirm, but my gut feeling is that in a casual data/ml pipeline a fair amount of process time is spent on preprocessing the data before getting to the first step of a scikit-learn pipeline in all that data cleaning and manipulation steps. And if those steps can benefit from switching to polars to the point that the overhead spent in sklearn part is compensated for, then it's worth switching.
Now even if that statement is true, a fundamental question would be: should we as sklearn care about that? Since users can independently choose what to do before and after sklearn, a jerk reaction answer might be no, but at the same time, it would feel weird if I go to teach people how to deal with data, and use polars, and then have only pandas on our examples. I really don't know.
One thing that I personally feel, is that we have a position to have an influence in ML engineers' choices, and that means we should think in the context of a whole workflow rather than sklearn only. But I'm also not completely set on whether that's the right position to have.
This has been a great thread, and I think to further the discussion, we need more data to make better informed decisions. I'll try to get the data. But it will take a while since I'd need a good chunk of time to focus on this. Checking the memory / CPU footprint of our examples would be a start.
Currently, we use copy=False when wrapping the ndarray to avoid the copy:
Right. That does not copy memory. And I think it is ok internally for scikit-learn IFF you regard it as move semantics. If you accept a matrix passed by a user. You must be very sure that columns in that DataFrame are not mutated as it will actually mutate the original memory, which is still hold by a users object.
Whether that's the case in scikit-learns transformers, I don't know...
importpandasaspdpd.set_option("mode.copy_on_write", True)
rows=int(1e8)
cols=5x=np.ones((rows, cols))
df=pd.DataFrame(x, copy=False)
# mutate column in DataFramedf.iloc[:, 0] =2.0# actually mutates the original memoryprint(x)
A lot of the conversations have been about memory copy. Although I enjoy the technical discussions, I want to share some of my experience in credit modelling. Again, the focus is in data, ML pipelines, because this is where dataframes are mostly used. (It is obviously very different in models. So I restrict to only pipelines.)
Transformations that are columnar: impute, scale, all algebraic combinations, clip, binning, any kind of encoding (target, woe, one-hot, rank-hot, etc.) which I argue is 80-90% of all traditional ML pipeline.
Most statistics are also columnar computations.
Non-columnar: PCA, which in my experience is very hard to put in production, and is mostly used as an exploratory tool.
I do not see any problem in copying data when doing things like PCA, unless someone is very resource constrained. I would highly recommend downsampling tech niques in that case.
For time series, I think it is inherently columnar. For things like auto-correlation coefficient, extra data have to be generated and we can generate matrices under the hood. So no real issue.
Entropy (e.g mutual info score) related stuff is better in matrices in theory, because you will need row wise data to be used as vector in R^n, for nearest neighbor searches.. However, the default implementations of kdtrees in scipy/sklearn copies data too. I argue that these things are again mostly used in exploration, not in production.
In conclusion, I don't think mem copy is as a big deal as it seems.
Whether that's the case in scikit-learns transformers, I don't know...
By default, scikit-learn estimators do not write to the underlying buffer. There are common tests to make sure that read-only NumPy arrays work with every estimator. (There are a few transformers with a copy parameter that allow for inplace operations, but there are not many.)
Yes, I agree a good chunk of ML pipelines are columnar, so there is a strong motivation to go DataFrame first. Currently, scikit-learn is supporting:
NumPy arrays
DataFrames by converting them to NumPy arrays
Array API arrays (To support GPUs using PyTorch or CuPy and can be a separate code path from NumPy)
If we go DataFrame native, we will better support the DataFrame use case. Functionally, there are two ways to do this:
Have a hard dependency on Polars (or Pandas) and then go through the DataFrame exchange protocol for all other DataFrames.
If I was unconstrained design-wise, I would want a hard dependency on Polars, just so I can create my own plugin expressions plugins and support polar's lazy DataFrames. Ideally, we'll have at most two code paths for every operation: "polars" and "Array API".
Reacted by Tianren Qin, Adrin Jalali, Marco Edward Gorelli, Stijn de Gooijer, Ritchie Vink, Meekail Zain, Christian Lorentzen, taozuoqiao and Pedro Barbosa
If I was unconstrained design-wise, I would want a hard dependency on Polars, just so I can create my own plugin expressions plugins and support polar's lazy DataFrames.
Realistically, this'll never happen. The spec isn't designed with Polars in mind. If you're concerned about an extra copy, you definitely wouldn't accept the compromises Polars would have to make to fit that spec.
I spent over half a year trying to turn things around, but it was an uphill battle which was affecting my mental health. Eventually I gave up.
Looks like skrub may have come to the same conclusion
hard dependency on Polars, just so I can create my own plugin expressions plugins and support polar's lazy DataFrames. Ideally, we'll have at most two code paths for every operation: "polars" and "Array API".
I think in this thread alone there are enough people motivated enough not only to make this happen but also to maintain it long-term (but just out of interest, why would it require a hard dependency?)
One addendum on the copy from/to numpy. In the new Polars release 0.20.7.
F-order numpy data can now be moved in and out of a Polars DataFrame zero-copy.
importpolarsasplimportnumpyasnprows=int(1e8)
cols=5x=np.ones((rows, cols), order='F')
# no-copydf=pl.DataFrame(x)
# no-copydf.to_numpy()
# But completely safe. We will never mutate# underlying data. If you do, we will simply# trigger a copy when you move data out into numpy
Why only F-order?
Because Polars is a columnar query engine, we only store F-contiguous data. Otherwise we would need to skip rows on column traversal. This would duplicate all code, or add an indirection for traversal which would be much slower.
Aside from that, you now have row values in your cache line, making all columnar algorithms much much slower.
C-contiguous
In c-contiguous, row values are back to back. If we need column_value we must skip nrow_x slots, where n is proportional on the number of columns.
So zero-copy C-contiguous data DataFrames comes with a performance cost for most operations (which are columnar) and might even trigger a copy if underlying columnar algorithms expect slices with data back to back (which isn't far fetched).
Reacted by stonebig
Reacted by Julien Jerphanion, Adrin Jalali, baggiponte, Meekail Zain, taozuoqiao and Abhishek Yadav
Now even if that statement is true, a fundamental question would be: should we as sklearn care about that? Since users can independently choose what to do before and after sklearn, a jerk reaction answer might be no, but at the same time, it would feel weird if I go to teach people how to deal with data, and use polars, and then have only pandas on our examples. I really don't know.
One thing that I personally feel, is that we have a position to have an influence in ML engineers' choices, and that means we should think in the context of a whole workflow rather than sklearn only. But I'm also not completely set on whether that's the right position to have.
I found this point interesting and worth bringing back up. My impression is that is sklearn goes X first, then people will rally around X, slowly but surely. For that reason, if core sklearn devs think that a certain technology would benefit users at large (including those that have no idea of memory/memmapping/__dataframe__ api/dtypes, then it would make sense to push the community in that direction.
I'm unsure how closely core pandas development interacts with sklearn's needs but it seems since @ritchie46 (polars dev) is interested in participating, it seems like the option could be quite good.
As for my perspective with writing tools on top of sklearn, it's pandas all the way right now. If there's any nuances with respect to user input into sklearn between pandas and polars, I would likely just stick with pandas only. Supporting two code paths with different levels of support is not something that I can maintained trivially.
Ok, it seems that we have the "2. Making scikit-learn dataframe native" discussion in this issue anyway. I few personal thoughts: I would love to have a dataframe native ML framework. I just don't know if its worth to turn scikit-learn into this or to make a new API design for it.
General considerations:
Which dataframe library should we choose to adapt? This has the potential of becoming an endless and fruitless discussion (polars, pandas, pass arrow using duckdb, ...). The more general, the more tradeoffs.
Which problem does it solve? Different people might have different problems in mind.
Polars specific:
Lazy frames are a key feature of polars. I don't see how that would work out in scikit-learn pipelines where the full data is passed from each step to the next.
Polars expressions are already a great API for data preparation pipelines. What's missing is the learning part (stateful transforms), i.e. my_lazy_df.with_columns(pl.col("A") - pl.col("A").mean()) only misses to save the mean of A in order to be applied later at prediction time (call of predict or transform) where the expression pl.col("A").mean() should get replaced by this saved value.
History [1]:
Keep in mind that the original design of scikit-learn was meant for matrix/2d-array data X, mostly with implied C-contiguity, and there are quite some use cases, too:
data from sensors
pairwise distances
etc (experts could fill many more point)
Then came the ColumnTransformer (v0.20) as an entry gate for heterogeneous tabular data, aka dataframes. But after the column transformer, all data is considered of the same data type. This made things like passing the information which column is categorical quite hard, see Programmatically pass categorical_features to HGBT #18894 (I'm still not 100% convinced of the solution: circumvent the pipeline with the ordinal encoder in the first place!)
With SLEP018 implemented in v1.2, estimators can output dataframes, but internally, (large) numpy arrays are processed, just the return value is wrapped in a dataframe (to my understanding).
Even in our current design and working with a 2d-array from the beginning, we still make a lot of data copies during the processing of a pipeline, potentially in each and every pipeline step.
[1] This is my understanding, I became a part of scikit-learn much later, and I'm not a historian.
As for my perspective with writing tools on top of sklearn, it's pandas all the way right now. If there's any nuances with respect to user input into sklearn between pandas and polars, I would likely just stick with pandas only.
To clarify, scikit-learn will continue to support pandas. An end user that only focuses on pandas will not need to worry about other dataframe libraries. With #28341 (comment), polars can be optional, so we would not impact any pandas-only workflows.
Lazy frames are a key feature of polars. I don't see how that would work out in scikit-learn pipelines where the full data is passed from each step to the next.
The scikit-learn transformer can also output lazy dataframes.1 In scikit-learn's Pipeline, the data is materialized when it reaches a step that requires the data in memory. For example, our trees will most likely require the data in memory, so it will be responsible to call df.collect().
Footnotes
I am leaving out details on how to manage stateful transformers with lazy DataFrames, but it's doable. ↩
Coming back to the original question of what to use in the examples: I think a lot of data science is of the form of operations that polars is good at, but I don't think that's captured well in our examples (at least it wasn't when I last checked them in detail). Maybe that changed, but using polars just to use polars seems strange. If we actually do significant preprocessing in any example, that would be a great way to showcase polars as input I think?
Activity
GaelVaroquaux commentedon Feb 1, 2024
glemaitre commentedon Feb 1, 2024
I agree with @GaelVaroquaux. I would be considering having a mix of example, even more when we don't take profit from polars features.
Currently our support for polars is closer to rewrapping a NumPy arrays into a Polars DataFrame without leveraging the lazyness.
In an ideal world, if we come to have estimator to leverage those features (e.g. via the dataframe API) then we should certainly demonstrate it in the documentation.
marenwestermann commentedon Feb 1, 2024
MarcoGorelli commentedon Feb 1, 2024
As far as I can tell, internally you're just using
__dataframe__(the dataframe interchange protocol) and__array__:__dataframe__: this is implemented natively without relying on pyarrow (thanks to a lot of work by the incredible @stinodego), and its API should be stable. Even if there's any internal change in Polars, the public API in__dataframe__shouldn't change (that's one good thing about standards!)__array__: for numeric and string datatypes, pyarrow isn't required (though it is required for Categorical). Pretty sure this one can be considered stable anywayAs for the API you'd use in the examples - there is a chance for deprecations to show up there, but there's also a well-written deprecation policy https://docs.pola.rs/development/versioning/#deprecation-period (note: the part at the end about breaking releases will be updated for the upcoming 1.0 release)
I've been having a hard time convincing the relevant people that those (lazy) features are a "must-have", so no promises that this will be possible I'm afraid. Input on data-apis/dataframe-api#346 would be appreciated (whether you agree, or whether I've misunderstood and am wrong)
thomasjpfan commentedon Feb 1, 2024
Panda's block manager that supports 2D arrays is still nicer memory-wise when it comes to the roundtrip:
numpy->dataframe->numpy. Pandas can hold on to numerical F-contiguous or C-contiguous NumPy array underneath the covers. This allows us to use Panda's dataframes in a scikit-learnPipelinewithout introducing memory overhead.I do not think polars is as a point where it can do the roundtrip without making a copy, which increasess memory usage. Because of this memory issue, I would still recommend converting polars dataframes to pandas before handing it over to scikit-learn's
Pipeline.With the memory issue in polars, I do not think we are in a good state to promote it's usage. I see two options to improve the situation around polars:
matmulwe need to be rethought)jorisvandenbossche commentedon Feb 1, 2024
I was mentioning the same memory issue, but @thomasjpfan already did that better just now
FWIW I don't expect any behaviour changes for the string dtype (you could also already test that with the latest pandas, which reminds me I should do a scikit-learn test run with pandas Copy-on-Write enabled). When converting to numpy, this still becomes object dtype, and I assume that's mostly the way that scikit-learn encounters it eventually.
(and nitpick: it's PyArrow, not "Arrow" in general, there are many Arrow implementations, including one embedded in polars ;))
lesteve commentedon Feb 1, 2024
FYI I did a quick and dirty attempt #27879 (comment). The preliminary result is that there are 2 failures but some of the issues may not be caught by our tests e.g. the one reported in #27879.
abstractqqq commentedon Feb 1, 2024
I did an experiment using only Polars (not even Numpy) for my ML pipelines during 2022-2023. I rewrote almost all Transformers and metrics using Polars + some Rust. Let me share my two cents on this issue:
Pros:

(1) You get the speed gain trivially. But this is not the most important factor.
(2) It is so much easier to write for Polars and Polars alone. (Polars in, Polars out)
Why? Because Polars enforces a strict type system. Polars has methods that internally handles null values, which makes Polars so much better than NumPy in practice. Imputation and scaling become trivial. No need to tons of if isinstance(...) and unnecessary branches. Once you start dealing with multiple output types, life gets harder..
(3) A lot more stuff can be written as Polars queries (heck even in SQL queries). ROC AUC can be computed as a SQL query and thus can be translated to Polars, and you can see the speed gain. Target encoding again can be computed as a SQL query and therefore can be rewritten in Polars... Thus using Polars, we can safely say goodbye to category_encoders.
(4) A transformer, in essence, is a function that outputs a recipe on how to replicate a mapping for some columns in the dataframe. As long as this recipe can be pickled, the same transform will work for training and testing, and all data splits. This is where Polars expressions come in. Almost all Polars's native expressions are pickle-able, so they can be reused. (I have not tested Polars plugin expression). This makes feature engineering again trivial in Polars.
Setting up a custom transfomer is a pain in current Sklearn because function transformers cannot be pickled properly. But say you want to do LogTransform. Do you really need all that inherited class nonsense? In polars you just do pl.col("a").log() and here you go this is your transformer. We run into this issue a lot in practice, where in our dataset we have feature A and B, but we need to use feature A/B. What we do now is to go back to SQL and add this feature. But during deployment, this adds work for Dev and sometimes the engineered feature gets complicated. Using Polars we can leave the SQL as it is. Pull only the raw feature set and keep feature engineering in Python in a VERY CLEAN way and everything is pickle-able and reusable so life is good. Using Transformer for this is not as clean, and for each project, the reusability of these transformers are suspicious. So I think expressions are superior in this case. We can therefore safely say goodbye to dependencies like Scikit-lego, feature-engine, or whatever feature engineering library that claims to be compatible with sklearn..
Cons:
(1) Backwards compatibility. Obviously a lot of things will need to be rewritten in Polars. This is not a con to me, but is a con to Sklearn the package.
(2) It might be harder to debug when running lazy polars. Because Lazy Polars won't stop at the exact point in the query to tell you what is wrong. Rather, it tells you what is wrong without telling you where exactly is the problem. That said, debugging in current sklearn can also be hard if you are using the BaseTransformers and other low-level classes.
I cannot really think of anything else.
Other comments:
(1) From my experience, for those who are doing traditional ML, the speed gain pointed out above does not matter so much. It's like 5s to 1s. Nothing critical unless you are serving stuff in real time, which is rare.
(2) I am the author of a package called polars-ds. If you are interested in doing data science with Polars and Rust, and like working with dataframe queries, then please check it out!
MarcoGorelli commentedon Feb 1, 2024
Hi @thomasjpfan - if the
.to_pandas()before passing to a scikit-learn Pipelineworkflow is the most memory-efficient one, then that might be a good one to show in examples?
thomasjpfan commentedon Feb 1, 2024
@MarcoGorelli
There are two types of examples:
fitand used duringtransform, then the example is to wrap the Polars expressions into a scikit-learn transformer.@abstractqqq scikit-learn's transformers is mostly about keeping track of state between
fitandtransform. For example:SimpleScalar, but it'll need some state object to hold on to the mean and std duringfittime. In this case, the state object can easily be another Polars DataFrame. Duringtransform, there needs to be another Polars expression that takes themeanandstdand uses it on new data. (Duringtransformtime, we do not need to compute the mean anymore).Due to the constraints of scikit-learn, I think it's better to look into Polars for ML in a separate project as you have done with
polars-ds. There is a good subset of ML techniques and algorithms that can make use of Polar's plugin system, and it is worth exploring.abstractqqq commentedon Feb 1, 2024
@thomasjpfan You are exactly right it is about keeping the states. But I think it boils down to two steps: (1) learn from train. We can learn the mean, std, from a Polars df, and this is multithreaded by default in Polars. (2) we can then pass these learned knowledge into expressions in Polars. E.g pl.col("a").fill_null(learned_value). Now this is a perfectly valid way of preserving states. Once we have a list of such expressions, we transform each at once, which again will be in parallel in Polars by default
adrinjalali commentedon Feb 1, 2024
@jorisvandenbossche this and this are where my concerns come from.
Context:
I don't know the details and if they're relevant here, but it could be.
ritchie46 commentedon Feb 1, 2024
Whatever the conclusions, this peeks my interest. ^^
Let's make clear what we can do on the Polars side.
Zero copy from a 2D numpy matrix to a Polars
DataFrameis possible in depending on the row-order. We can memory map the columns.Zero copy from a Polars
DataFrameto to numpy matrix will not be possible. However, we heavily parallelized the copy, and don't expect it to be the bottleneck. I expect there are quite some implicit copies in a current implementations.1D columnar (without nulls) will be completely zero-copy in both directions.
2D numpy matrix (without nulls) will be completely zero-copy to the Polars
Arraydata-type and back.We will implement the numpy array interface very soon and that will follow the above rules on (zero)-copyness.
adrinjalali commentedon Feb 1, 2024
So it seems a [to be confirmed with benchmarks] summary of this thread is:
sklearnsteps might be / most probably are quite faster onpolarssklearn.Pipelinestepspandasmight be faster, due to lack of memory copies.I'm not sure, and I would need to see benchmarks to confirm, but my gut feeling is that in a casual data/ml pipeline a fair amount of process time is spent on preprocessing the data before getting to the first step of a scikit-learn pipeline in all that data cleaning and manipulation steps. And if those steps can benefit from switching to polars to the point that the overhead spent in sklearn part is compensated for, then it's worth switching.
Now even if that statement is true, a fundamental question would be: should we as sklearn care about that? Since users can independently choose what to do before and after sklearn, a jerk reaction answer might be no, but at the same time, it would feel weird if I go to teach people how to deal with data, and use polars, and then have only pandas on our examples. I really don't know.
One thing that I personally feel, is that we have a position to have an influence in ML engineers' choices, and that means we should think in the context of a whole workflow rather than sklearn only. But I'm also not completely set on whether that's the right position to have.
This has been a great thread, and I think to further the discussion, we need more data to make better informed decisions. I'll try to get the data. But it will take a while since I'd need a good chunk of time to focus on this. Checking the memory / CPU footprint of our examples would be a start.
5 remaining items
ritchie46 commentedon Feb 3, 2024
Right. That does not copy memory. And I think it is ok internally for scikit-learn IFF you regard it as move semantics. If you accept a matrix passed by a user. You must be very sure that columns in that DataFrame are not mutated as it will actually mutate the original memory, which is still hold by a users object.
Whether that's the case in scikit-learns transformers, I don't know...
abstractqqq commentedon Feb 3, 2024
A lot of the conversations have been about memory copy. Although I enjoy the technical discussions, I want to share some of my experience in credit modelling. Again, the focus is in data, ML pipelines, because this is where dataframes are mostly used. (It is obviously very different in models. So I restrict to only pipelines.)
Transformations that are columnar: impute, scale, all algebraic combinations, clip, binning, any kind of encoding (target, woe, one-hot, rank-hot, etc.) which I argue is 80-90% of all traditional ML pipeline.
Most statistics are also columnar computations.
Non-columnar: PCA, which in my experience is very hard to put in production, and is mostly used as an exploratory tool.
I do not see any problem in copying data when doing things like PCA, unless someone is very resource constrained. I would highly recommend downsampling tech niques in that case.
For time series, I think it is inherently columnar. For things like auto-correlation coefficient, extra data have to be generated and we can generate matrices under the hood. So no real issue.
Entropy (e.g mutual info score) related stuff is better in matrices in theory, because you will need row wise data to be used as vector in R^n, for nearest neighbor searches.. However, the default implementations of kdtrees in scipy/sklearn copies data too. I argue that these things are again mostly used in exploration, not in production.
In conclusion, I don't think mem copy is as a big deal as it seems.
thomasjpfan commentedon Feb 3, 2024
By default, scikit-learn estimators do not write to the underlying buffer. There are common tests to make sure that read-only NumPy arrays work with every estimator. (There are a few transformers with a
copyparameter that allow for inplace operations, but there are not many.)Yes, I agree a good chunk of ML pipelines are columnar, so there is a strong motivation to go DataFrame first. Currently, scikit-learn is supporting:
If we go DataFrame native, we will better support the DataFrame use case. Functionally, there are two ways to do this:
If I was unconstrained design-wise, I would want a hard dependency on Polars, just so I can create my own plugin expressions plugins and support polar's lazy DataFrames. Ideally, we'll have at most two code paths for every operation: "polars" and "Array API".
glemaitre commentedon Feb 3, 2024
I think this is where we are heading to in
skrub(https://github.com/skrub-data/skrub/) taking profit that we don't have the same constraints.MarcoGorelli commentedon Feb 3, 2024
Realistically, this'll never happen. The spec isn't designed with Polars in mind. If you're concerned about an extra copy, you definitely wouldn't accept the compromises Polars would have to make to fit that spec.
I spent over half a year trying to turn things around, but it was an uphill battle which was affecting my mental health. Eventually I gave up.
Looks like skrub may have come to the same conclusion
I think in this thread alone there are enough people motivated enough not only to make this happen but also to maintain it long-term (but just out of interest, why would it require a hard dependency?)
thomasjpfan commentedon Feb 3, 2024
You are right, polars can be a soft dependency. If we get a DataFrame, then the behavior could be:
ritchie46 commentedon Feb 5, 2024
One addendum on the copy from/to numpy. In the new Polars release
0.20.7.F-ordernumpy data can now be moved in and out of a PolarsDataFramezero-copy.Why only F-order?
Because Polars is a columnar query engine, we only store
F-contiguousdata. Otherwise we would need to skip rows on column traversal. This would duplicate all code, or add an indirection for traversal which would be much slower.Aside from that, you now have
rowvalues in your cache line, making all columnar algorithms much much slower.C-contiguous
In c-contiguous, row values are back to back. If we need
column_valuewe must skipnrow_xslots, wherenis proportional on the number of columns.F-contiguous
In f-contiguous, column slots are back to back, leading to fast cache efficient reading
So zero-copy
C-contiguousdataDataFramescomes with a performance cost for most operations (which are columnar) and might even trigger a copy if underlying columnar algorithms expect slices with data back to back (which isn't far fetched).eddiebergman commentedon Feb 5, 2024
I found this point interesting and worth bringing back up. My impression is that is sklearn goes
Xfirst, then people will rally aroundX, slowly but surely. For that reason, if core sklearn devs think that a certain technology would benefit users at large (including those that have no idea of memory/memmapping/__dataframe__ api/dtypes, then it would make sense to push the community in that direction.I'm unsure how closely core pandas development interacts with sklearn's needs but it seems since @ritchie46 (polars dev) is interested in participating, it seems like the option could be quite good.
As for my perspective with writing tools on top of sklearn, it's pandas all the way right now. If there's any nuances with respect to user input into sklearn between pandas and polars, I would likely just stick with pandas only. Supporting two code paths with different levels of support is not something that I can maintained trivially.
lorentzenchr commentedon Feb 5, 2024
Ok, it seems that we have the "2. Making scikit-learn dataframe native" discussion in this issue anyway. I few personal thoughts:
I would love to have a dataframe native ML framework. I just don't know if its worth to turn scikit-learn into this or to make a new API design for it.
General considerations:
Polars specific:
my_lazy_df.with_columns(pl.col("A") - pl.col("A").mean())only misses to save the mean of A in order to be applied later at prediction time (call ofpredictortransform) where the expressionpl.col("A").mean()should get replaced by this saved value.History [1]:
X, mostly with implied C-contiguity, and there are quite some use cases, too:ColumnTransformer(v0.20) as an entry gate for heterogeneous tabular data, aka dataframes. But after the column transformer, all data is considered of the same data type. This made things like passing the information which column is categorical quite hard, see Programmatically pass categorical_features to HGBT #18894 (I'm still not 100% convinced of the solution: circumvent the pipeline with the ordinal encoder in the first place!)[1] This is my understanding, I became a part of scikit-learn much later, and I'm not a historian.
thomasjpfan commentedon Feb 5, 2024
To clarify, scikit-learn will continue to support pandas. An end user that only focuses on pandas will not need to worry about other dataframe libraries. With #28341 (comment), polars can be optional, so we would not impact any pandas-only workflows.
The scikit-learn transformer can also output lazy dataframes.1 In scikit-learn's
Pipeline, the data is materialized when it reaches a step that requires the data in memory. For example, our trees will most likely require the data in memory, so it will be responsible to calldf.collect().Footnotes
I am leaving out details on how to manage stateful transformers with lazy DataFrames, but it's doable. ↩
amueller commentedon Feb 12, 2024
Coming back to the original question of what to use in the examples: I think a lot of data science is of the form of operations that polars is good at, but I don't think that's captured well in our examples (at least it wasn't when I last checked them in detail). Maybe that changed, but using polars just to use polars seems strange. If we actually do significant preprocessing in any example, that would be a great way to showcase polars as input I think?
glemaitre commentedon Feb 12, 2024
I thought about this example (while it does not use any scikit-learn transformers): https://scikit-learn.org/dev/auto_examples/applications/plot_time_series_lagged_features.html#sphx-glr-auto-examples-applications-plot-time-series-lagged-features-py
adrinjalali commentedon Jun 13, 2025
We now have polars in different places and we support it as a dataframe. I think we can close this now.
lorentzenchr commentedon Jun 16, 2025
cross ref #25896