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

相关推荐
神仙别闹19 小时前
基于Python + SQL server 实现(GUI)原神圣遗物管理与角色数值模拟系统
java·数据库·python
是有头发的程序猿19 小时前
电商自动化实战:淘宝/天猫item_get商品详情API全量采集教程(Python源码)
java·python·自动化
_不会dp不改名_19 小时前
python-opencv环境搭建
开发语言·python·opencv
勇往直前plus19 小时前
智能体记忆概述
人工智能·python·ai
HappyAcmen20 小时前
9.复盘API全套流程
开发语言·python
zh路西法20 小时前
【Linux 串口通信】基于 C++ 多线程的同步/异步串口实现
linux·运维·c++·python
北暮城南20 小时前
使用 Claude Code 高效实现图像边缘检测:多算法对比与工程实践
python·opencv·numpy·matplotlib·边缘检测·claude code
装不满的克莱因瓶20 小时前
学习并掌握 LangChain 检索器的作用,实现让 LLM 动态调用知识库功能
人工智能·python·ai·langchain·llm·agent·智能体
devnullcoffee21 小时前
亚马逊 Buy Box 数据采集完全指南(2026):Python 实战 + Pangolinfo API
开发语言·python·亚马逊数据采集·亚马逊数据 api·pangolinfo api·亚马逊 buy box 数据·亚马逊数据采集软件
imDwAaY21 小时前
贝叶斯网络到粒子滤波Python算法实现 CS188 Proj4 学习笔记
网络·人工智能·笔记·python·学习·算法