『sklearn学习』沃德结构层次聚类的浣熊脸图像的演示

# 沃德结构层次聚类的浣熊脸图像的演示
# A demo of structured Ward hierarchical clustering on a raccoon face image
import time as time

import numpy as np
import scipy as sp

import matplotlib.pyplot as plt

from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version

if sp_version < (0, 12):
    raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and"
                   "thus does not include the scipy.misc.face() image.")

# 创建数据
try:
    face = sp.face(gray=True)
except AttributeError:
    # 较新版本的 scipy 的 face 函数放在 misc 中
    # Newer versions of scipy have face in misc
    from scipy import misc
    face = misc.face(gray=True)

# 调整到原始尺寸的 10%,以加快处理
# Resize it to 10% of the original size to speed up the processing
face = sp.misc.imresize(face, 0.10) / 255.0      # 为什么要除以 255

X = np.reshape(face, (-1, 1))

# 定义数据的结构,连接到他们相邻的像素
# Define the structure A of the data, Pixels connected to their neighbors
connectivity = grid_to_graph(*face.shape)

# 计算聚类
print "Compute structured hierarchical clustering..."
st = time.time()
n_clusters = 15    # 区域的数量
# 此处传入的参数 connectivity 的作用是什么?不加入的话则运行时间要长得多,且图像效果也跟加入的差别很大
ward = AgglomerativeClustering(n_clusters=n_clusters, linkage="ward", connectivity=connectivity)
ward.fit(X)
label = np.reshape(ward.labels_, face.shape)
print "Elapsed time: ", time.time() - st
print "Number of pixels: ", label.size
print "Number of clusters: ", np.unique(label).size

# 将结果绘制在图上
# Plot the results on an image
plt.figure(figsize=(5, 5))
plt.imshow(face, cmap=plt.cm.gray)
for cluster_num in range(n_clusters):
    plt.contour(label == cluster_num, contours=1, colors=[plt.cm.spectral(cluster_num / float(n_clusters)), ])
plt.xticks(())
plt.yticks(())
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值