基于Python——Kmeans聚类算法的实现
2020-06-28 08:55:55 来源:易采站长站 作者:易采站长站整理
# ----------------------------->读入数据,创建数据集并划分训练集和测试集对图片进行聚类<--------------------------------------#
# 获得图片的宽、高、颜色深度
w, h, d = img.shape
# 展开成n*3维的矩阵,-1代表自适应
img = np.array(img.reshape(-1, 3), dtype=np.float64)
# -----------------------------使用曼哈顿距离进行聚类-----------------------------
plt.figure()
plt.subplot(3, 1, 1)
print("使用曼哈顿距离聚类开始。。。。。。。")
# 建立Kmeans分类
estimator = KMeans(n_cluster=5, algorithm=manhattan_distance) # 默认是使用欧式距离计算
# 使用训练集来聚类,找到每个种类对应的簇中心
estimator.fit(x_train)
# 根据训练好的结果,对整个图像进行聚类
y_predict = estimator.predict(img)
# 将聚类结果显示
image = recreate_image(estimator.cluster_centers_, y_predict, w, h)
plt.title("使用曼哈顿距离聚类所得的图像")
plt.imshow(image)
# -----------------------------使用欧式距离进行聚类-----------------------------
# 建立Kmeans分类
plt.subplot(3, 1, 2)
print("使用欧式距离聚类开始。。。。。。。")
estimator = KMeans(n_cluster=5, algorithm=euclid_distance) # 默认是使用欧式距离计算
# 使用训练集来聚类,找到每个种类对应的簇中心
estimator.fit(x_train)
# 根据训练好的结果,对整个图像进行聚类
y_predict = estimator.predict(img)
# 将聚类结果显示
image = recreate_image(estimator.cluster_centers_, y_predict, w, h)
plt.title("使用欧式距离聚类所得的图像")
plt.imshow(image)
# -----------------------------使用切比雪夫距离进行聚类-----------------------------
# 建立Kmeans分类
plt.subplot(3, 1, 3)
print("使用切比雪夫距离聚类开始。。。。。。。")
estimator = KMeans(n_cluster=5, algorithm=chebyshev_distance) # 默认是使用欧式距离计算
# 使用训练集来聚类,找到每个种类对应的簇中心
estimator.fit(x_train)
# 根据训练好的结果,对整个图像进行聚类
y_predict = estimator.predict(img)
# 将聚类结果显示
image = recreate_image(estimator.cluster_centers_, y_predict, w, h)
plt.title("使用切比雪夫距离聚类所得的图像")
plt.imshow(image)
plt.show()
因为聚类是无监督的学习算法,所以一般来说是不会用来分类的。评价一个聚类模型的好坏,可以根据模型的轮廓系数来判定,至于这个轮廓系数是啥东西,大家可以参考sklearn关于Kmeans的说明,或者百度,Google。













闽公网安备 35020302000061号