从 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嵌套列类型

相关推荐
IVEN_5 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang6 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮7 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling7 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮10 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽10 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers