美文网首页
非监督Kmeans和DBSCAN算法代码实践

非监督Kmeans和DBSCAN算法代码实践

作者: 万州客 | 来源:发表于2022-04-29 08:59 被阅读0次

撸到一半了。

一,代码

import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN

blobs = make_blobs(random_state=1, centers=1)
X_blobs = blobs[0]

# db = DBSCAN(eps=2)
db = DBSCAN(min_samples=20)
clusters = db.fit_predict(X_blobs)
plt.scatter(X_blobs[:, 0], X_blobs[:, 1], c=clusters, cmap=plt.cm.cool,
            s=60, edgecolors='k')
plt.xlabel('Feature 0')
plt.ylabel('Feature 1')
plt.show()
'''

kmeans = KMeans(n_clusters=3)
kmeans.fit(X_blobs)
# plt.scatter(X_blobs[:, 0], X_blobs[:, 1], c='r', edgecolors='k')
# plt.show()
x_min, x_max = X_blobs[:, 0].min() - 0.5, X_blobs[:, 0].max() + 0.5
y_min, y_max = X_blobs[:, 1].min() - 0.5, X_blobs[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),
                     np.arange(y_min, y_max, .02))
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
           extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap=plt.cm.summer,
           aspect='auto', origin='lower')
plt.plot(X_blobs[:, 0], X_blobs[:, 1], 'r', markersize=5)
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
            marker='x', s=150, linewidths=3,
            color='b', zorder=10)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
'''

二,效果


2022-04-26 22_37_24-MessageCenterUI.png 2022-04-26 22_32_07-MessageCenterUI.png

相关文章

网友评论

      本文标题:非监督Kmeans和DBSCAN算法代码实践

      本文链接:https://www.haomeiwen.com/subject/zzahyrtx.html