[551]python实现Mean Shift算法

前文介绍的K-Means算法需要指定K值(分组数),本文实现的MeanShift聚类算法不需要预先知道聚类的分组数,对聚类的形状也没有限制。

为了更好的理解这个算法,本帖使用Python实现Mean Shift算法。

MeanShift算法详细介绍:https://en.wikipedia.org/wiki/Mean_shift

scikit-learn中的MeanShift
import numpy as np
from sklearn.cluster import MeanShift
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets.samples_generator import make_blobs
 
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
 
# 生成3组数据样本
centers = [[2,1,3], [6,6,6], [10,8,9]]
x,_ = make_blobs(n_samples=200, centers=centers, cluster_std=1)
#for i in range(len(x)):
#    ax.scatter(x[i][0], x[i][1], x[i][2])

image.png

# 对上面数据进行分组
clf = MeanShift()
clf.fit(x)
 
labels = clf.labels_    # 每个点对应的组
cluster_centers = clf.cluster_centers_  # 每个组的"中心点"
#print(labels)
print(cluster_centers)
 
colors = ['r', 'g', 'b']
for i in range(len(x)):
    ax.scatter(x[i][0], x[i][1], x[i][2], c=colors[labels[i]])
 
ax.scatter(cluster_centers[:,0], cluster_centers[:,1], cluster_centers[:,2], marker='*', c='k', s=200, zorder=10)
 
pyplot.show()

image.png

MeanShift把上面数据自动分为3组,计算出的三个组的”中心点”为:

[[  1.97566619   1.04212548   3.02410725]
 [  6.01672157   6.18325271   5.96562957]
 [ 10.14455378  12.02394435   9.03499578]]
# 和[[2,1,3], [6,6,6], [10,12,9]]接近;生成的样本越多越接近
使用Python实现Mean Shift算法
# -*- coding:utf-8 -*-
import numpy as np
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets.samples_generator import make_blobs


class MeanShift(object):
    def __init__(self, bandwidth=4):
        #bandwidth参数代表点的半径(radius)范围
        self.bandwidth_ = bandwidth

    def fit(self, data):
        centers = {}
        # 把每个点都当做中心点
        for i in range(len(data)):
            centers[i] = data[i]
            # print(centers)
        while True:
            new_centers = []
            for i in centers:
                in_bandwidth = []
                # 取一个点,把在范围内的其它点放到in_bandwidth
                center = centers[i]
                for feature in data:
                    # self.bandwidth_越小分的组越多
                    if np.linalg.norm(feature - center) < self.bandwidth_:
                        in_bandwidth.append(feature)

                new_center = np.average(in_bandwidth, axis=0)
                new_centers.append(tuple(new_center))

            uniques = sorted(list(set(new_centers)))
            prev_centers = dict(centers)
            centers = {}
            for i in range(len(uniques)):
                centers[i] = np.array(uniques[i])

            optimzed = True
            for i in centers:
                if not np.array_equal(centers[i], prev_centers[i]):
                    optimzed = False
                    if not optimzed:
                        break
            if optimzed:
                break

        self.centers_ = centers


if __name__ == '__main__':
    fig = pyplot.figure()
    ax = fig.add_subplot(111, projection='3d')
    centers = [[2, 1, 3], [6, 6, 6], [10, 12, 9]]
    x, _ = make_blobs(n_samples=18, centers=centers, cluster_std=1)
    clf = MeanShift()
    clf.fit(x)
    print(clf.centers_)
    for i in clf.centers_:
        ax.scatter(clf.centers_[i][0], clf.centers_[i][1], clf.centers_[i][2], marker='*', c='k', s=200, zorder=10)

    for i in range(len(x)):
        ax.scatter(x[i][0], x[i][1], x[i][2])

    pyplot.show()

执行结果:

使用Python实现Mean Shift算法

bandwidth参数代表点的半径(radius)范围,bandwidth=20:

使用Python实现Mean Shift算法

bandwidth=2.5:

使用Python实现Mean Shift算法

这个bandwidth可以根据数据样本求出最适合的值。

# -*- coding:utf-8 -*-
import numpy as np
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets.samples_generator import make_blobs


class MeanShift(object):

    def __init__(self, bandwidth=None, bandwidth_step=100):
        self.bandwidth_ = bandwidth
        self.bandwidth_step_ = bandwidth_step

    def fit(self, data):
        if self.bandwidth_ == None:
            all_data_center = np.average(data, axis = 0)
            self.bandwidth_ = np.linalg.norm(all_data_center) /self.bandwidth_step_
        print(self.bandwidth_)
        centers = {}
        # 把每个点都当做中心点
        for i in range(len(data)):
            centers[i] = data[i]
            # print(centers)
        while True:
            new_centers = []
            for i in centers:
                in_bandwidth = []
                # 取一个点,把在范围内的其它点放到in_bandwidth
                center = centers[i]
                w = [i for i in range(self.bandwidth_step_)][::-1]
                for feature in data:
                    distance = np.linalg.norm(feature - center)
                    if distance == 0:
                        distance = 0.000000001
                    w_index = int(distance /self.bandwidth_)
                    if w_index > self. bandwidth_step_ -1:
                        w_index = self. bandwidth_step_ -1
                    in_bandwidth += (w[w_index] **2) * [feature]

                new_center = np.average(in_bandwidth, axis=0)
                new_centers.append(tuple(new_center))

            uniques = sorted(list(set(new_centers)))
            tmp = []
            for i in uniques:
                for ii in uniques:
                    if i == ii:
                        pass
                    elif np.linalg.norm(np.array(i) - np.array(ii)) <= self.bandwidth_:
                        tmp.append(ii)
                        break
            for i in tmp:
                try:
                    uniques.remove(i)
                except:
                    pass

            prev_centers = dict(centers)
            centers = {}
            for i in range(len(uniques)):
                centers[i] = np.array(uniques[i])

            optimzed = True
            for i in centers:
                if not np.array_equal(centers[i], prev_centers[i]):
                    optimzed = False
                    if not optimzed:
                        break
            if optimzed:
                break

        self.centers_ = centers

    def predict(self, data):
        self.labels_ = {}
        for i in range(len(centers)):
            self.labels_[i] = []
        for feature in data:
            distances = [np.linalg.norm(feature - self.centers_[center]) for center in self.centers_]
            clf = distances.index(min(distances))
            self.labels_[clf].append(feature)
在实际数据上应用Mean Shift算法

数据集:titanic.xls(泰坦尼克号遇难者/幸存者名单)。目的:对乘客进行分类,看看这几组人有什么共同特点。

# -*- coding:utf-8 -*-
import numpy as np
from sklearn.cluster import MeanShift,estimate_bandwidth

from sklearn import preprocessing
import pandas as pd


'''
数据集:titanic.xls(泰坦尼克号遇难者/幸存者名单)
<http://blog.topspeedsnail.com/wp-content/uploads/2016/11/titanic.xls>
***字段***
pclass: 社会阶层(1,精英;2,中层;3,船员/劳苦大众)
survived: 是否幸存
name: 名字
sex: 性别
age: 年龄
sibsp: 哥哥姐姐个数
parch: 父母儿女个数
ticket: 船票号
fare: 船票价钱
cabin: 船舱
embarked
boat
body: 尸体
home.dest
******
目的:使用除survived字段外的数据进行means shift分组,看看能分为几组,这几组人有什么共同特点
'''

# 加载数据
df = pd.read_excel('titanic.xls')
# print(df.shape)  (1309, 14)
# print(df.head())
# print(df.tail())
"""
    pclass  survived                                            name     sex  \
0       1         1                    Allen, Miss. Elisabeth Walton  female
1       1         1                   Allison, Master. Hudson Trevor    male
2       1         0                     Allison, Miss. Helen Loraine  female
3       1         0             Allison, Mr. Hudson Joshua Creighton    male
4       1        G 0  Allison, Mrs. Hudson J C (Bessie Waldo Daniels)  female

       age  sibsp  parch  ticket      fare    cabin embarked boat   body  \
0  29.0000      0      0   24160  211.3375       B5        S    2    NaN
1   0.9167      1      2  113781  151.5500  C22 C26        S   11    NaN
2   2.0000      1      2  113781  151.5500  C22 C26        S  NaN    NaN
3  30.0000      1      2  113781  151.5500  C22 C26        S  NaN  135.0
4  25.0000      1      2  113781  151.5500  C22 C26        S  NaN    NaN

    home.dest
0                     St Louis, MO
1  Montreal, PQ / Chesterville, ON
2  Montreal, PQ / Chesterville, ON
3  Montreal, PQ / Chesterville, ON
4  Montreal, PQ / Chesterville, ON
"""

org_df = pd.DataFrame.copy(df)

# 去掉无用字段
df.drop(['body', 'name'], 1, inplace=True)

df.convert_objects(convert_numeric=True)#将object格式转float64格式
df.fillna(0, inplace=True)  # 把NaN替换为0

# 把字符串映射为数字,例如{female:1, male:0}
df_map = {}  # 保存映射
cols = df.columns.values
for col in cols:
    if df[col].dtype != np.int64 and df[col].dtype != np.float64:
        temp = {}
        x = 0
        for ele in set(df[col].values.tolist()):
            if ele not in temp:
                temp[ele] = x
                x += 1

        df_map[df[col].name] = temp
        df[col] = list(map(lambda val: temp[val], df[col]))

for key, value in df_map.items():
   print(key,value)
# print(df.head())

# 由于是非监督学习,不使用label
x = np.array(df.drop(['survived'], 1).astype(float))
# 将每一列特征标准化为标准正太分布,注意,标准化是针对每一列而言的
x = preprocessing.scale(x)

clf = MeanShift()
clf.fit(x)

labels = clf.labels_
cluster_centers = clf.cluster_centers_
print('labels:',labels)
print('cluster_centers:',cluster_centers)
n_cluster = len(np.unique(labels))
print('n_cluster:',n_cluster)

org_df['group'] = np.nan
for i in range(len(x)):
    org_df['group'].iloc[i] = labels[i]

survivals = {}
for i in range(n_cluster):
    temp_df = org_df[org_df['group'] == float(i)]
    survival_cluster = temp_df[(temp_df['survived'] == 1)]
    survial = 1.0 * len(survival_cluster) / len(temp_df)
    survivals[i] = survial
print(survivals)

# MeanShift自动把数据分成了三组,每组对应的生还率为(有时分成4组):
# {0: 0.37782982045277125, 1: 0.8333333333333334, 2: 0.1}
# 你可以详细分析一下org_df, 看看这几组人的共同特点是什么
# print(org_df[ org_df['group'] == 2 ])
# print(org_df[ org_df['group'] == 2 ].describe())
org_df.to_excel('group.xls')

来源:http://blog.topspeedsnail.com/archives/10366

### 回答1: meanshift算法是一种聚类算法,它可以用于图像分割、目标跟踪等领域。在Python,可以使用scikit-learn库MeanShift类来实现算法。该类提供了fit方法来拟合数据,并返回聚类的心点。同时,也可以使用predict方法来预测新的数据点所属的聚类。在使用该算法时,需要设置带宽参数,该参数决定了聚类的精度和速度。 ### 回答2: meanshift是一种图像分割算法,用于检测图像的物体。该算法通过将数据点聚合成密度最大的区域来运作,即将每个数据点移动到其周围的局部密度最大的区域的心。在不断地移动数据点后,最后形成的聚类即为图像的物体。 在python,我们可以使用sklearn库Meanshift类来实现meanshift算法。首先,我们需要导入所需的库: ```python from sklearn.cluster import MeanShift, estimate_bandwidth import numpy as np import cv2 ``` 然后,我们可以读取我们想要分割的图像: ```python img = cv2.imread('your_image_path') ``` 接下来,我们需要将图像转换为数据点数组。在这里,我们需要将每个像素的坐标和RGB值组合成一个3维向量,作为我们的数据点。可以使用以下代码实现: ```python #获取图像尺寸 rows, cols, _ = img.shape #将图像转化为2D数组,并将每个像素的坐标和RGB值组合成3维向量 X = np.reshape(img, (rows*cols, 3)) ``` 现在,我们需要估计簇的带宽大小。这个带宽大小将决定聚类结果的密度。我们可以使用`estimate_bandwidth`函数来计算带宽大小。 ```python #估计带宽大小 bandwidth = estimate_bandwidth(X, quantile=0.1, n_samples=100) ``` 之后,我们可以使用`Meanshift`类来聚类数据点,并获得聚类结果。 ```python #初始化Meanshift对象,并执行聚类 ms = MeanShift(bandwidth=bandwidth, bin_seeding=True) ms.fit(X) #获取聚类结果 labels = ms.labels_ ``` 最后,我们可以将聚类结果转换为图像,并显示出来。 ```python #重构图像形状 label_reshape = np.reshape(labels, (rows, cols)) #显示聚类结果图像 cv2.imshow('Segmented Image', label_reshape) cv2.waitKey(0) ``` 以上是meanshift算法python实现过程,我们可以根据特定的应用场景和数据特征进行参数的调整,以达到更好的分割效果。 ### 回答3: meanshift算法是一种非参数方法,用于从一个多维概率密度函数寻找极大值。它通常被用于图像分割和计算机视觉领域。 下面介绍如何用Python实现meanshift算法: 首先,我们需要引入numpy和matplotlib库: ```python import numpy as np import matplotlib.pyplot as plt ``` 然后,读取图像并将图像进行平滑化处理。 ```python # 读取图像并转换为numpy数组 img = plt.imread('test.jpg') # 将图像转换为二维数组 img_arr = np.array(img) # 将图像进行平滑化处理 from sklearn.cluster import MeanShift, estimate_bandwidth # 估计带宽值 bandwidth = estimate_bandwidth(img_arr, quantile=0.1, n_samples=100) # 建立Meanshift模型 ms = MeanShift(bandwidth=bandwidth, bin_seeding=True) # 模型拟合 ms.fit(img_arr) # 提取标签 labels = ms.labels_ # 提取类别数量 n_clusters_ = len(np.unique(labels)) ``` 然后,我们通过绘制不同的颜色来表示图像的不同区域。 ```python # 创建一个空白的图像,用于绘制结果 segmented_img = np.zeros_like(img_arr) # 遍历所有标签并给每个区域着色 for label in np.unique(labels): # 根据标签生成掩码 mask = labels == label # 将掩码应用于原始图像并着色 segmented_img[mask] = np.random.randint(0, 255, 3) # 绘制结果 plt.figure(figsize=(10, 5)) plt.subplot(121) plt.imshow(img_arr) plt.title('Original Image') plt.axis('off') plt.subplot(122) plt.imshow(segmented_img) plt.title('Segmented Image') plt.axis('off') plt.show() ``` 最后,我们可以得到分割后的图像。 Meanshift算法Python实现过程比较简单,但是需要注意的是,在图像分割,需要通过调整带宽来得到合适的分割效果。此外,还可以通过调整其他参数和超参数来进一步改进算法的性能和精度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值