You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在Polars中使用Scikit-learn的PCA并保留CustomerID

如何在Polars中使用Scikit-learn的PCA并保留CustomerID

我完全懂你遇到的困扰——Polars不像Pandas有索引机制,直接用PCA拟合特征列会丢CustomerID,错误把CustomerID当y参数传入又搞砸了后续聚类。下面给你两种实用的解决思路,核心都是把CustomerID和特征分离处理,最后再合并回去

方法一:分离特征与ID,转换后合并

这是最直观清晰的方式,步骤一目了然:

  1. 先把CustomerID列单独提取出来,剩下的列作为PCA的特征数据
  2. 用Scikit-learn的PCA拟合并转换特征数据
  3. 将转换后的PCA结果转回Polars DataFrame,再和CustomerID列合并

代码示例:

import polars as pl
from sklearn.decomposition import PCA

# 假设你的缩放后数据集是customer_data_scaled
# 1. 拆分CustomerID和特征列
customer_ids = customer_data_scaled.select("CustomerID__CustomerID")
feature_data = customer_data_scaled.select(pl.all().exclude("CustomerID__CustomerID"))

# 2. 初始化PCA(可以指定需要的主成分数量,比如2个)并拟合转换
pca = PCA(n_components=2)
# Polars DataFrame转numpy数组供sklearn处理
pca_transformed = pca.fit_transform(feature_data.to_numpy())

# 3. 把PCA结果转成Polars格式,再和ID横向合并
pca_df = pl.DataFrame(
    pca_transformed,
    columns=[f"PC{i+1}" for i in range(pca_transformed.shape[1])]
)
final_result = customer_ids.hstack(pca_df)

处理后,final_result里同时保留了CustomerID和对应的主成分数据,完全能支撑后续的聚类或分析需求。

为什么你之前的第二种方法行不通?

你尝试把y="CustomerID"传入fit方法,这是对Scikit-learn无监督算法的误解:PCA是无监督模型,fit方法里的y参数只是为了和监督学习模型的接口统一,实际不会参与模型训练,所以传入CustomerID根本不会影响PCA的结果。你说的“所有信息卡在第一簇”应该是后续聚类步骤的问题,和这个PCA调用方式无关,但这种用法本身就是错误的,建议别再这么用。

额外小提醒

  • 确保feature_data里的所有列都是数值型,Polars转numpy时如果有非数值列会报错,所以提前排除CustomerID是必要的
  • 如果需要后续关联原始数据的其他列,可以用final_result.join(customer_data_scaled, on="CustomerID__CustomerID")来实现

备注:内容来源于stack exchange,提问作者Simon

火山引擎 最新活动