python - 如何根据时间戳而不是位置查找地理空间数据集群?
问题描述
我有一组地理空间数据,在单独的列中也有相应的时间戳。
像这样的东西:
时间戳 | 纬度 | 经度 |
---|---|---|
1 | 1.56 | 104.57 |
2 | 1.57 | 105.42 |
4 | 1.65 | 103.32 |
12 | 1.76 | 101.15 |
14 | 1.78 | 100.45 |
16 | 1.80 | 99.65 |
我希望能够根据时间戳而不是距离对数据进行聚类。
所以对于上面的例子,我应该获得 2 个集群:1 个来自第 3 个数据点,1 个来自剩余的 3 个。我还想获得每个集群的时间戳范围是可能的。
从我到目前为止的研究来看,我只得到了地理空间距离聚类或时间序列聚类,这两种方法听起来都不是我需要的。对于我正在尝试做的事情,有什么推荐的算法吗?
解决方案
在这里,基于密度的噪声应用程序空间聚类或DBSCAN算法将对您的情况有所帮助。DBSCAN是一种基于密度的聚类算法,它根据点之间的接近程度对点进行分组。
根据我在快速研究中的理解,DBSCAN 在其核心周围画了一个圆圈。圆的半径称为epsilon。单个圆圈内的所有点都将计入同一个簇中。epsilon越大,集群中的点数就越多,反之亦然。
为什么 DBSCAN 适合时间序列聚类:
DBSCAN 不需要 k(簇数)作为输入
在您的情况下,可能有许多时间段集群。尝试拟合肘部曲线以找到最佳数量的集群将是耗时且低效的。
代码:
下面的代码片段将完成您的任务,
import pandas as pd
from sklearn.cluster import DBSCAN
import numpy as np
import matplotlib.pyplot as plt
# Getting Data
df = pd.DataFrame({
'Timestamp' : [1,2,4,12,14,16,25,28,29],
'Latitude' : [1.56,1.57,1.65,1.76,1.78,1.80,1.83,1.845,1.855],
'Longitude' : [104.57,105.42,103.32,101.15,100.45,99.65,100,100.3,101.2]})
# Initializing the object
db = DBSCAN(eps=3.0, min_samples=3)
# eps = Epsilon value. Larger the epsilon, the more distant points you will catch in a single cluster.
# Ex. eps = 1.0 wasn't capturing the '4' value from [1,2,4] cluster. Increasing the epsilon
# helped in detecting that.
# min_samples = Minimum number of samples you want in your single cluster.
# Fitting the algorithm onto Timestamp column
df['Cluster'] = db.fit_predict(np.array(df['Timestamp']).reshape(-1,1))
print(f"Found {df['Cluster'].nunique()} clusters \n")
print(df)
# Plotting the Graph
fig = plt.figure(figsize = (5,5))
plt.xlabel('Latitude')
plt.ylabel('Longitude')
for data in df.groupby(df['Cluster']):
index = data[0]
df = data[1]
plt.scatter(df['Latitude'], df['Longitude'], c=np.random.rand(1,len(df)), label=f"Cluster {index}")
plt.legend()
plt.show()
输出:
推荐阅读
- python - Python f-string:替换换行符/换行符
- node.js - 运行reactjs第一个代码后如何修复错误
- android - 导航组件底部导航中的主页图标按下
- python - 将python字典的值作为数据导入现有的mysql表
- ios - Swift - 将数据从父视图控制器传递到子视图控制器
- typescript - 在其他类中调用方法后,如何使用“this”获取实例
- java - 创建一个目录来分别存放源文件和类文件。但是,我无法在同一个包中将一个类扩展到另一个类
- visual-studio - 为什么我在 unit3d 上而不是在 Visual Studio 上出现此错误
- sh - 检测是否尝试删除 `.bash_aliases` 中的文件夹
- caching - 从纯粹缓存的角度来看,使用新的 Cache API 代替常规的 http 缓存有什么优势吗?