在学习机器的过程中,发现了K-means的一种应用,遂那这个例子,练练手,增加对K-means的理解。
# -- encoding:utf-8 --
"""
Create by yexm on 2018/11/24
"""
# coding:utf-8
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from sklearn import metrics
def im_resize(imgData,pixel=64):
w,h,rgb = imData.shape
img = 0
if rgb == 3 or rgb == 1:
img = np.array(imData,dtype=np.float32)/255
else:
img = imData
img0 = img.reshape(-1, rgb)
x_train = shuffle(img0, random_state=28)#打乱数据
algo = KMeans(n_clusters=pixel)
algo.fit(x_train[:2000,:])
x_class = algo.predict(img0)
center = algo.cluster_centers_#各个簇中心坐标
n=0
img1 = np.zeros([w, h, rgb])
for i in range(w):
for j in range(h):
index = x_class[n]
data = center[index]#用簇中心的值代表该簇内其他点的值
img1[i,j]= data
n+=1
km_y_hat2 = algo.labels_
print(metrics.silhouette_score(img0, x_class))#打印出轮廓系数(即聚类衡量的一种指标)
return img1
if __name__ == "__main__":
imData = plt.imread('143731404.jpg')#读取当前目录下的图片
imDataNew = im_resize(imData, pixel=64)#pixel值的是簇的数据即我们长说K-means中的K
plt.imshow(imDataNew)
plt.show()