Python uses kmeans one-dimensional clustering and two-dimensional clustering

        Use python's sklearn library to do kmeans one-dimensional clustering and two-dimensional clustering.

        I searched online, recorded it, and was doing histogram clustering.

1. kmeans one-dimensional clustering

        This mainly depends on a reshape(-1, 1). Kmeans clustering is generally two-dimensional clustering, and if one dimension is needed, it must be transformed. This is also a hint that comes with it:

         a is a one-dimensional array list. The code is:

from sklearn.cluster import KMeans

x = a.reshape(-1,1)
myKmeans = KMeans(n_clusters = 3)     # 聚类成3团
myKmeans.fit(x)
centers = list(myKmeans.cluster_centers_)
print(centers)

        Note that the list does not have reshape, you can use np.array() to convert it:

a = np.array(a)

2. kmeans two-dimensional clustering

        This mainly requires a two-dimensional list. Both two-dimensional lists and two-dimensional arrays should work.

         The code change is not big: just assign the two-dimensional list to x

from sklearn.cluster import KMeans

x = 二维列表
myKmeans = KMeans(n_clusters = 3)     # 聚类成3团
myKmeans.fit(x)
centers = list(myKmeans.cluster_centers_)
print(centers)

        The result should be:

 

Guess you like

Origin blog.csdn.net/weixin_43907136/article/details/128043087