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

相关推荐
人工智能AI技术6 分钟前
【Agent从入门到实践】44 监控与日志:添加监控指标、日志记录,方便问题排查
人工智能·python
2301_8174973318 分钟前
自然语言处理(NLP)入门:使用NLTK和Spacy
jvm·数据库·python
weixin_5500831531 分钟前
QTdesigner配置在pycharm里使用anaconda环境配置安装成功
ide·python·pycharm
强化试剂瓶32 分钟前
Silane-PEG8-DBCO,硅烷-聚乙二醇8-二苯并环辛炔技术应用全解析
python·flask·numpy·pyqt·fastapi
钱多多先森44 分钟前
【Dify】使用 python 调用 Dify 的 API 服务,查看“知识检索”返回内容,用于前端溯源展示
开发语言·前端·python·dify
zhougl9961 小时前
Java定时任务实现
java·开发语言·python
ZPC82101 小时前
ROS2 独占内核
人工智能·python·算法·机器人
qq_381454991 小时前
Python Pandas完全指南:从核心数据结构到实战操作
pandas
hcnaisd21 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python