我正在使用一个数据集,其中包含一个城市中各个点的经度和纬度数据。我已经应用了DBSCAN群集,并且已经计算了群集的质心。
我已经成功完成了对大叶草地图上的点进行地理编码和绘图,但是我找不到在地图上绘制聚类的方法(我正在使用Python)。
我如何在叶片图上可视化这些簇的形状?
# data_1 contains a columof longitude and a column for latitude
coords = data_1.as_matrix(columns=['Origin_Latitude', 'Origin_Longitude']) # DBSCAN
kms_per_radian = 6371
epsilon = 1.5/kms_per_radian
db = DBSCAN(eps=epsilon,
min_samples=1,
algorithm='ball_tree',
metric='haversine').fit(np.radians(coords))
cluster_labels = db.labels_
num_clusters = len(set(cluster_labels))
clusters = pd.Series( [coords[cluster_labels==n] for n in range(num_clusters)] )
# Plotting all points from folium.plugins
import MarkerCluster from folium import plugins
some_map_1 = folium.Map(location=[data_1['Origin_Latitude'].mean(), data_1['Origin_Longitude'].mean()], zoom_start=25)
mc = MarkerCluster()
j = 0
row = 0
for row in range(len(clusters)):
for j in range(len(clusters[row])):
mc.add_child(folium.Marker(location=[clusters[row][j][0],clusters[row][j][1]], popup=row))
some_map_1.add_child(mc)
some_map_1
这样的事情应该为您做。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import seaborn as sns; sns.set()
import csv
df = pd.read_csv('C:\\your_path\\properties_2017.csv')
# df.head(10)
df = df.head(10000)
df.shape
df.dropna(axis=0,how='any',subset=['latitude','longitude'],inplace=True)
# Variable with the Longitude and Latitude
X=df.loc[:,['parcelid','latitude','longitude']]
X.head(10)
K_clusters = range(1,10)
kmeans = [KMeans(n_clusters=i)
for i in K_clusters]
Y_axis = df[['latitude']]
X_axis = df[['longitude']]
score = [kmeans[i].fit(Y_axis).score(Y_axis)
for i in range(len(kmeans))] # Visualize
plt.plot(K_clusters, score)
plt.xlabel('Number of Clusters')
plt.ylabel('Score')
plt.title('Elbow Curve')
plt.show()
kmeans = KMeans(n_clusters = 3, init ='k-means++')
kmeans.fit(X[X.columns[1:3]]) # Compute k-means clustering.X['cluster_label'] = kmeans.fit_predict(X[X.columns[1:3]])centers = kmeans.cluster_centers_ # Coordinates of cluster centers.labels = kmeans.predict(X[X.columns[1:3]]) # Labels of each pointX.head(10)
X['cluster_label'] = kmeans.fit_predict(X[X.columns[1:3]])
centers = kmeans.cluster_centers_ # Coordinates of cluster centers.
labels = kmeans.predict(X[X.columns[1:3]]) # Labels of each pointX.head(10)
X.head(5)
X = X[['parcelid','cluster_label']]
X.head(5)
parcelid cluster_label
0 10754147 0
1 10759547 0
2 10843547 2
3 10859147 2
4 10879947 2
clustered_data = df.merge(X, left_on='parcelid', right_on='parcelid')
clustered_data.head(5)
centers = kmeans.cluster_centers_
print(centers)
X=df.loc[:,['parcelid','latitude','longitude']]
X.plot.scatter(x = 'latitude', y = 'longitude', c=labels, s=50, cmap='viridis')
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)
数据源:
https://www.kaggle.com/xxing9703/kmean-clustering-of-latitude-and-longitude/data