from pylab import imread,imshow,figure,show,subplot
from numpy import reshape,flipud
from sklearn.cluster import KMeans
from copy import deepcopy,copy
img = imread('./data/sample2.jpeg')
# reshape the picture
pixel = reshape(img,(img.shape[0]*img.shape[1],3))
pixel_new = deepcopy(pixel)print(img.shape)
model = KMeans(n_clusters=10)
labels = model.fit_predict(pixel)
palette = model.cluster_centers_
#print(palette)for i inrange(len(pixel)):
pixel_new[i,:]=palette[labels[i]]
imshow(reshape(pixel_new,(img.shape[0],img.shape[1],3)))
基于K-means的用户分层
import pandas as pd
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
#choosing K=5
kmeans_5 = KMeans(n_clusters =5).fit_predict(table)
points =list(kmeans_5)
d ={x:points.count(x)for x in points}
heights =list(d.values())
plt.bar(range(5),heights)
plt.xlabel('Cluster')
plt.xlabel('# of sample')