使用python使用DBSCAN算法在给定x,y,z坐标时聚类3D点

时间:2019-05-09 15:19:05

标签: python-3.x

我正在尝试使用DBSCAN算法和python在某些给定坐标的帮助下对一些3D点进行聚类。

ex:-给定的坐标如下

  X      Y      Z

 [-37.530  3.109  -16.452]
 [40.247  5.483  -15.209]
 [-31.920 12.584  -12.916] 
 [-32.760 14.072  -13.749]
 [-37.100  1.953  -15.720] 
 [-32.143 12.990  -13.488]
 [-41.077  4.651  -15.651] 
 [-34.219 13.611  -13.090]
 [-33.117 15.875  -13.738]  e.t.c

我对编程和寻找示例脚本(如何编写代码)很陌生。有人可以提出建议或例子吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用sklearn.cluster.DBSCAN。就您而言:

import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import DBSCAN

data = np.array([[-37.530, 3.109, -16.452],
                [40.247, 5.483, -15.209],
                [-31.920, 12.584, -12.916],
                [-32.760, 14.072, -13.749],
                [-37.100, 1.953, -15.720],
                [-32.143, 12.990, -13.488],
                [-41.077, 4.651, -15.651], 
                [-34.219, 13.611, -13.090],
                [-33.117, 15.875, -13.738]])

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(data[:,0], data[:,1], data[:,2], s=300)
ax.view_init(azim=200)
plt.show()

model = DBSCAN(eps=2.5, min_samples=2)
model.fit_predict(data)
pred = model.fit_predict(data)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(data[:,0], data[:,1], data[:,2], c=model.labels_, s=300)
ax.view_init(azim=200)
plt.show()

print("number of cluster found: {}".format(len(set(model.labels_))))
print('cluster for each point: ', model.labels_)

输出

  • 聚类之前

enter image description here

  • 聚类后

enter image description here

number of cluster found: 3
cluster for each point:  [ 0 -1  1  1  0  1 -1  1  1]