You need to enable JavaScript to run this app. 如何在scikit聚类算法中忽略factorize后转为-1的NaN值
优惠活动
大模型
产品
解决方案
定价
更多

如何在scikit聚类算法中忽略factorize后转为-1的NaN值

方案1:过滤包含-1的样本行(适配你当前使用的ward linkage参数)

仅保留所有列取值均≥0的样本参与聚类,逻辑最简单,无需调整原有聚类参数:

import pandas as pd
from sklearn.cluster import AgglomerativeClustering

# 原有编码逻辑不变
z = df.apply(lambda x: pd.factorize(x)[0])
# 新增过滤逻辑:仅保留所有列都≥0的行,排除含-1的样本
z_filtered = z[z.ge(0).all(axis=1)]
# 用过滤后的数据执行聚类
cluster = AgglomerativeClustering(n_clusters=None, distance_threshold=10, affinity='euclidean', linkage='ward')
cluster_labels = cluster.fit_predict(z_filtered)

注意:该方案会丢弃所有包含-1的样本,若你的样本量较少不建议使用


方案2:保留全部样本,-1不参与距离计算

如果不想丢弃样本,可以先将-1替换为NaN,用支持缺失值的欧氏距离预计算距离矩阵,再调整聚类参数适配预计算的距离:

import pandas as pd
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics.pairwise import nan_euclidean_distances

z = df.apply(lambda x: pd.factorize(x)[0])
# 将-1替换为NaN,用于后续缺失值距离计算
z_nan = z.replace(-1, np.nan)
# 预计算样本间距离,计算时自动忽略NaN(即原-1值)
dist_matrix = nan_euclidean_distances(z_nan)
# 调整聚类参数:affinity设为预计算,ward不支持预计算距离,可更换为average/complete等linkage
cluster = AgglomerativeClustering(n_clusters=None, distance_threshold=10, affinity='precomputed', linkage='average')
cluster_labels = cluster.fit_predict(dist_matrix)

注意:该方案需调整linkage参数,原有distance_threshold可能需要根据新的距离分布重新调整


可选优化:删除全为-1的无效列

从你提供的z样例来看,最后几列全为-1没有有效信息,可以先删除这部分列减少计算量:

z = z.loc[:, z.ge(0).any(axis=0)]

内容的提问来源于stack exchange,提问作者Murcie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 07:54:00