You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否有Python库可对三维数组做层次聚类以提取代表性日期?

需求可行性结论

该需求完全可以实现,仅靠Python生态现有成熟的开源库即可完成全流程开发,无需自定义复杂聚类逻辑。

核心实现逻辑

你的聚类目标是「日期」维度,每个日期对应24小时、8个时间序列的特征集合,仅需将单天的所有特征拉平为一维向量,即可适配常规层次聚类算法的输入要求,聚类完成后从每个簇中提取代表性原始日期,按原结构拼接即可得到符合要求的(N-days,24-hours,8-time series)输出。

所需依赖库
  • 基础数组运算使用numpy即可完成
  • 层次聚类直接调用scipy.cluster.hierarchy模块,支持所有常用的层次聚类规则与距离计算方式
  • 若8个时间序列量纲差异较大,可使用scikit-learn的StandardScaler做标准化,避免特征权重失衡
  • 若需要考虑时序偏移相似度,可使用dtw-python计算DTW距离替换默认欧式距离
核心实现步骤
  1. 数据预处理:按需对每个时间序列做标准化,再将原始(365,24,8)数组的单天特征拉平,转换为(365, 192)的二维数组,每行对应1天的所有特征
  2. 聚类拟合:调用层次聚类接口生成聚类树,按需求指定聚类数量N
  3. 代表日期提取:每个聚类簇中选取距离簇中心最近的原始日期作为代表,保留该日期的(24,8)原始结构
  4. 结果拼接:将N个代表日期的结构拼接,得到最终输出数组
参考代码示例
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.preprocessing import StandardScaler

# 原始输入数据,形状为(365, 24, 8),此处为随机生成的示例数据
raw_data = np.random.rand(365, 24, 8)

# 可选步骤:对8个时间序列分别做标准化,消除量纲影响
scaler = StandardScaler()
scaled_data = scaler.fit_transform(raw_data.reshape(-1, 8)).reshape(365, 24, 8)

# 拉平单天特征,适配聚类输入要求
cluster_input = scaled_data.reshape(365, -1)

# 层次聚类拟合,使用沃德法+欧式距离,可按需调整参数
linkage_matrix = linkage(cluster_input, method="ward", metric="euclidean")

# 指定需要提取的代表性日期数量N
N = 10
cluster_labels = fcluster(linkage_matrix, t=N, criterion="maxclust")

# 提取每个簇的代表性日期
represent_days = []
for cluster_id in range(1, N+1):
    # 获取当前簇的所有样本
    cluster_mask = cluster_labels == cluster_id
    cluster_samples = cluster_input[cluster_mask]
    # 计算簇中心
    cluster_center = cluster_samples.mean(axis=0)
    # 选取距离簇中心最近的样本作为代表
    dist_to_center = np.linalg.norm(cluster_samples - cluster_center, axis=1)
    closest_sample_local_idx = np.argmin(dist_to_center)
    closest_sample_global_idx = np.where(cluster_mask)[0][closest_sample_local_idx]
    # 保留原始数据结构加入结果集
    represent_days.append(raw_data[closest_sample_global_idx])

# 转换为数组,输出形状为(N, 24, 8)
result = np.array(represent_days)
print(result.shape)
可选优化方向
  • 若业务场景对时序的平移相似度要求高,可将聚类使用的距离替换为DTW距离,更符合时间序列的相似度判定逻辑
  • 可按需调整代表性日期的选取规则,例如选取簇内中位数样本,或贴合业务规则选取特定日期作为代表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:45:03