从 Pandas 到 Polars 三十六:直接从Polars适配Scikit-learn和XGBoost模型

可以使用Polars来适配机器学习模型而不需要Numpy吗?

Polars DataFrame中的数据是以Apache Arrow表的形式存储的,而不是Numpy数组。在早期,这意味着我们必须在将数据用于机器学习库之前手动将其转换为Numpy数组。

比如广泛应用于各种机器学习任务的XGBoost分布式梯度增强库和非常流行的机器学习库scikit-learn。

然而,现在情况已经不同了。在这篇文章中,我们将看到如何直接从Polars DataFrame适配XGBoost和一些scikit-learn模型。不过,这个过程还没有完全结束------在内部,数据很可能会被复制到库所偏好的格式。

让我们创建一个带有一些随机数据的Polars DataFrame,看看我们是否可以直接从中适配一个XGBoost模型。

python 复制代码
import polars as pl
import xgboost as xgb

# Set the number of rows in the DF
N = 100
# Create the DF with 2 features and a label
df = (
    pl.DataFrame(
        {
            # Use pl.arange to create a sequence of integers
            "feat1":pl.arange(0,N,eager=True),
            # Shuffle the sequence for the second feature
            "feat2":pl.arange(0,N,eager=True).shuffle(),
            # Create a label with 0s and 1s
            "label":[0]*(N//2) +  [1]*(N//2)
        }
    )
)

model = xgb.XGBClassifier(objective='binary:logistic')
# Fit the model
# X  = df.select("feat1","feat2")
# y = df.select("label")
model.fit(
    X = df.select("feat1","feat2"),
    y= df.select("label")
)
# Add the prediction probabilities to the DF
df = pl.concat([
        df,
        pl.DataFrame(model.predict_proba(X)[:,1],schema=["pos"])
],
    how="horizontal"
)

这些都有效,我们可以让XGBoost处理任何数据转换。

现在让我们尝试使用scikit-learn中的逻辑回归模型。

python 复制代码
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(df.select("feat1","feat2"),df.select("label"))
model.predict(df.select("feat1","feat2"))

这同样可以工作。

请注意,scikit-learn 目前在内部从 Polars 复制到 Numpy,但有了这种支持,我们朝着全面原生支持 Arrow 数据迈进了一步。

目前并非所有 scikit-learn 的模型和流程都支持 Polars,但这仍然是一个巨大的进步。

往期热门文章:

从 Pandas 到 Polars 二十六:在Polars中,不要遍历列

从 Pandas 到 Polars 二十三:如果你的数据已经排序,Polars可以为你提供助力

从 Pandas 到 Polars 十八:数据科学 2025,对未来几年内数据科学领域发展的预测或展望

从 Pandas 到 Polars 十三:流式处理的关键参数

从 Pandas 到 Polars 十:"Polars 表达式"是什么?

从 Pandas 到 Polars 六:在 Polars 中流式处理大型数据集

从 Pandas 到 Polars 0:理解Polars嵌套列类型

相关推荐
郭庆汝5 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络8 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find9 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取11 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector12 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习12 小时前
Python入门Day2
开发语言·python
Vertira12 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉12 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗13 小时前
黑马python(二十四)
开发语言·python