python简单实现c均值算法
时间: 2023-11-25 20:50:21 浏览: 50
以下是Python实现c均值算法的简单示例:
```python
import numpy as np
def c_means_clustering(data, c, m, error):
# 初始化隶属度矩阵
U = np.random.rand(len(data), c)
U = np.divide(U, np.sum(U, axis=1)[:, None])
while True:
# 计算聚类中心
centroids = np.dot(data.T, U) / np.sum(U, axis=0)[:, None]
# 计算距离矩阵
distances = np.sqrt(np.sum((data[:, None] - centroids.T) ** 2, axis=2))
# 更新隶属度矩阵
U_new = np.power(distances, -2/(m-1))
U_new = np.divide(U_new, np.sum(U_new, axis=1)[:, None])
# 计算误差
error_new = np.sum(np.abs(U_new - U))
# 判断是否收敛
if error_new < error:
break
U = U_new
return U
# 示例数据
data = np.array([[1, 2], [2, 1], [3, 4], [4, 3]])
c = 2
m = 2
error = 0.01
# 聚类
U = c_means_clustering(data, c, m, error)
# 输出隶属度矩阵
print(U)
```
阅读全文