基于Python——Kmeans聚类算法的实现
2020-06-28 08:55:55 来源:易采站长站 作者:易采站长站整理
return total
距离算法公式实现(calculate_distance_algorithm.py):
import numpy as np
def manhattan_distance(x1, x2):
"""
计算两点间的曼哈顿距离
:param x1:(x1, y1)
:param x2:(x2, y2)
:return:返回两点之间的曼哈顿距离
"""
result = np.abs(x1[0] - x2[0]) + np.abs(x1[1] - x1[1])
return resultdef chebyshev_distance(x1, x2):
"""
计算两点间的切比雪夫距离
:param x1:(x1, y1)
:param x2:(x2, y2)
:return:返回两点之间的切比雪夫距离
"""
return np.max(np.abs(x1 - x2))
def euclid_distance(x1, x2):
"""
计算两点间的欧式距离
:param x1:(x1, y1)
:param x2:(x2, y2)
:return: 返回两点之间的欧式距离
"""
return np.sqrt(np.sum((x1 - x2) ** 2))
下面给出使用Kmeans聚类算法对图片进行聚类的实现。
聚类图片对象为:
聚类结果图像:

测试代码:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import cv2 as cv
from K_means import KMeans
from calculate_distance_algorithm import manhattan_distance, chebyshev_distance, euclid_distancedef recreate_image(clusters, labels, w, h):
"""
重新创建图像
:param clusters: 聚类中心
:param labels: 预测的种类集合
:param w: 图像的宽
:param h: 图像的高
:return: 返回图像
"""
d = clusters.shape[1] # 构建图像 w:宽, h:高, d:聚类个数
# print(clusters)
image = np.zeros((w, h, d))
label_idx = 0
for i in range(w):
for j in range(h):
image[i][j] = clusters[labels[label_idx]] # print(image[i][j])
label_idx += 1
return image
def get_data(data, k):
"""
将对应的三维数组转换成 n*4维的矩阵,前3列是数据,最后一列是该类数据对应的样本标签值k
:param data: 数据
:param k: 标签
:return: 转换好的n*4维数据
"""
# 展开成n*3维
data = data.reshape(-1, 3)
# 生成颜色对应的标签
data_label = np.ones((data.shape[0], 1))
data_label *= k
# 将标签列与数据合并
return np.hstack((data, data_label))
if __name__ == '__main__':













闽公网安备 35020302000061号