Kmeans基本原理
机器学习按照有无标签可以分为"监督学习"和"非监督学习"。
监督学习里的代表算法就是:SVM、逻辑回归、决策树、各种继承算法等等。
非监督学习主要的任务就是通过一定的规则,把相似的数据聚集到一起,简称聚类。
K-means算法是在非监督学习里比较容易理解的一个算法,也是聚类算法中最著名的算法。
K-means是典型的聚类算法。
K-means算法中的K表示的是聚类为K个簇,means代表每一个聚类中数据值的均值作为该簇的中心,或成为质心。
即用每一个的类的质心对该簇进行描述。
K-means步骤
1、创建K个点作为起始质心。
2、计算每一个数据点到K个质心的距离。把这个点归到距离最近的哪个质心。
3、根据每个质心所聚集的点,重新更新质心的位置。
4、重复2-3步,直到前后两次质心的位置的变化小于一个阈值。
API地址:
https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans
举例:
>>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [10, 2], [10, 4], [10, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X) #用这段训练好模型 fix(X)为传入基础数据
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> kmeans.predict([[0, 0], [12, 3]]) #使用模型训练新的数据,即传入新的数据给模型
array([1, 0], dtype=int32)
>>> kmeans.cluster_centers_ #返回训练数据的质心点
array([[10., 2.],
[ 1., 2.]])
Methods(方法)
fit(X[, y, sample_weight]) Compute k-means clustering
fit_predict(X[, y, sample_weight]) Compute cluster centers and predict cluster index for each sample.
训练用户的基础数据和预测用的数据是同一份数据,可使用此方法
Attributes(属性)
cluster_centers_ ndarray of shape (n_clusters, n_features),Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.
labels_ ndarray of shape (n_samples,) Labels of each point
inertia_ float,Sum of squared distances of samples to their closest cluster center.
n_iter_ int,Number of iterations run.
判断此模型是否是可行的,如果返回值接近于1代表可行,如果返回值接近-1大表不可行。
sklearn.metrics.silhouette_score(X, labels, *, metric='euclidean', sample_size=None, random_state=None, **kwds)

K-means模型举例.png
网友评论