学习了k-means,k-means实现聚类是无监督算法,k-means的优点是:速度快,简单,适合常规数据集。
缺点是:k的选取,复杂度和样本呈线性关系,很难发现任意形状的簇。
附上一个k-means可视化的链接:
https://www.naftaliharris.com/blog/visualizing-k-means-clustering/
选择样本数据,这里我选择一个smiley face数据,分成4类,效果如下:
感兴趣的可以自己试一试。下面是k-means实现图像压缩:
from skimage import io
from sklearn.cluster import KMeans
import numpy as np
image=io.imread('timg.jpg')
io.imshow(image)
io.show()
rows=image.shape[0]
cols=image.shape[1]
image=image.reshape(image.shape[0]*image.shape[1],3) #3通道
kmeans=KMeans(n_clusters=128,n_init=10,max_iter=200) #像素的取值范围限制在0-128
kmeans.fit(image)
clusters=np.asarray(kmeans.cluster_centers_,dtype=np.uint8)
labels=np.asarray(kmeans.labels_,dtype=np.uint8)
labels=labels.reshape(rows,cols)
print(clusters.shape)
np.save('codebook_tiger.npy',clusters)
io.imsave('compressed_timg.jpg',labels)
我使用的图片是一只老虎
显示压缩后的老虎:
image=io.imread('compressed_timg.jpg')
io.imshow(image)
io.show()
可以看出老虎的大体轮廓 。