python - 首先基于属性和距离矩阵对观测值进行聚类
问题描述
我有一个包含位置(坐标)和每个位置的标量属性(例如温度)的数据集。我需要根据标量属性对位置进行聚类,但要考虑位置之间的距离。
问题在于,以温度为例,相距较远的位置可能具有相同的温度。如果我在温度上进行集群,这些位置将在同一个集群中,而它们不应该在同一个集群中。如果彼此靠近的两个位置具有不同的温度,则相反。在这种情况下,基于温度的聚类可能会导致这些观测值位于不同的聚类中,而基于距离矩阵的聚类会将它们放在同一个聚类中。
那么,有没有一种方法可以对观察结果进行聚类,更加重视一个属性(温度),然后根据距离矩阵“细化”?
这是一个简单的示例,显示了聚类如何根据属性是用作基础还是距离矩阵而有所不同。我的目标是能够同时使用属性和距离矩阵,更加重视属性。
import numpy as np
import matplotlib.pyplot as plt
import haversine
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial import distance as ssd
# Create location data
x = np.random.rand(100, 1)
y = np.random.rand(100, 1)
t = np.random.randint(0, 20, size=(100,1))
# Compute distance matrix
D = np.zeros((len(x),len(y)))
for k in range(len(x)):
for j in range(len(y)):
distance_pair= haversine.distance((x[k], y[k]), (x[j], y[j]))
D[k,j] = distance_pair
# Compare clustering alternatives
Zt = linkage(t, 'complete')
Zd = linkage(ssd.squareform(D), method="complete")
# Cluster based on t
clt = fcluster(Zt, 5, criterion='distance').reshape(100,1)
plt.figure(figsize=(10, 8))
plt.scatter(x, y, c=clt)
plt.show()
# Cluster based on distance matrix
cld = fcluster(Zd, 10, criterion='distance').reshape(100,1)
plt.figure(figsize=(10, 8))
plt.scatter(x, y, c=cld)
plt.show()
haversine.py 可在此处获得:https ://gist.github.com/rochacbruno/2883505
谢谢。
解决方案
推荐阅读
- kubernetes - 如何自动更新集群中的 Istio 资源?
- go - 如何在 go 模板中排列数组的一部分?
- maven - 如何使用 mvn wildfly:run 命令部署两个项目
- angular2-template - NG0303:即使在导入 CommonModule 之后,也无法绑定到“ngIf”
- visual-studio-code - 在函数内部保留空行
- java - 关于包含类加载器的说明
- apache-kafka - ksqldb,问题设置模式注册表
- mysql - MySQL 基于列值运行总计
- google-cloud-platform - 使用 ansible 在 GCP 计算引擎上访问 vm 的外部 ip
- python - 在 Python 中:如何输入一个数字 x 并打印 x 次,每次增加 2