Python机器学习

均值漂移算法

Python机器学习均值漂移算法详细操作教程

均值漂移算法简介

如前所述,这是用于无监督学习中的另一种强大的聚类算法。与K均值聚类不同,它没有做任何假设;因此它是一种非参数算法。
平均移位算法基本上是通过将数据点移向最高密度的数据点(即群集质心)来迭代地将数据点分配给群集。
K-Means算法与Mean-Shift的区别在于,后一种算法无需事先指定聚类数,因为聚类数将由w.r.t数据算法确定。

均值漂移算法的工作

借助以下步骤,我们可以了解均值漂移聚类算法的工作原理-
步骤1-首先,从分配给它们自己的群集的数据点开始。 步骤2-接下来,该算法将计算质心。 步骤3-在这一步中,新质心的位置将被更新。 步骤4-现在,该过程将被迭代并移至更高密度的区域。 步骤5-最后,一旦质心到达无法进一步移动的位置,它将停止。

Python的实现

这是一个简单的示例,用于了解均值漂移算法的工作原理。在此示例中,我们将首先生成包含4个不同Blob的2D数据集,然后将应用Mean-Shift算法查看结果。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-26
%matplotlib inline
import numpy as np
from sklearn.cluster import MeanShift
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.datasets.samples_generator import make_blobs
centers = [[3,3,3],[4,5,5],[3,10,10]]
X, _ = make_blobs(n_samples = 700, centers = centers, cluster_std = 0.5)
plt.scatter(X[:,0],X[:,1])
plt.show()
平均移位算法
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-26
ms = MeanShift()
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
print(cluster_centers)
n_clusters_ = len(np.unique(labels))
print("Estimated clusters:", n_clusters_)
colors = 10*['r.','g.','b.','c.','k.','y.','m.']
for i in range(len(X)):
   plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 3)
plt.scatter(cluster_centers[:,0],cluster_centers[:,1],
   marker = ".",color = 'k', s = 20, linewidths = 5, zorder = 10)
plt.show()

输出

# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-26
[[ 2.98462798 9.9733794 10.02629344]
[ 3.94758484 4.99122771 4.99349433]
[ 3.00788996 3.03851268 2.99183033]]
Estimated clusters: 3
生成数据集

优缺点

优势

以下是Mean-Shift聚类算法的一些优点-
它不需要像K-means或高斯混合中那样做出任何模型假设。 它还可以对非凸形状的复杂簇进行建模。 它只需要一个名为带宽的参数即可自动确定群集数。 没有像K-means中那样的局部最小值问题。 离群值没有问题。

缺点

以下是Mean-Shift聚类算法的一些缺点-
在高维情况下(簇数突然变化),均值漂移算法效果不佳。 我们无法直接控制集群的数量,但是在某些应用程序中,我们需要特定数量的集群。 它无法区分有意义的模式和无意义的模式。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4