import numpy as npfrom numpy.linalg import normdef fcm(X, c, m, error=0.0001, maxiter=1000): # 初始化隶属度矩阵 U U = np.random.rand(c, X.shape[0]) U /= np.sum(U, axis=0) # 迭代计算 for i in range(maxiter): # 计算聚类中心 centroids = U.dot(X) / U.sum(axis=1)[:, None] # 计算距离矩阵 distances = np.sqrt(((X[:, None, :] - centroids) ** 2).sum(axis=2)) # 更新隶属度矩阵 U U_new = 1 / (distances / np.expand_dims(np.min(distances, axis=2), axis=2)) ** (2 / (m - 1)) U_new /= np.sum(U_new, axis=0) # 判断收敛 if norm(U_new - U) < error: break U = U_new # 返回聚类结果 return centroids, U.argmax(axis=0)# 示例数据X = np.random.rand(100, 2)# 聚类数目c = 3# 模糊指数m = 2# 聚类centroids, labels = fcm(X, c, m)# 打印聚类中心和标签print('Centroids:', centroids)print('Labels:', labels)优化这段代码
时间: 2023-11-23 12:05:41 浏览: 136
这段代码本身已经比较简洁和高效了,但还是有一些可以优化的地方:
1. 在计算距离矩阵时,可以使用numpy的广播功能来避免使用np.expand_dims函数:
```
distances = np.sqrt(((X[:, None, :] - centroids) ** 2).sum(axis=2))
```
2. 在计算U_new时,可以将np.expand_dims函数替换为np.newaxis:
```
U_new = 1 / (distances / np.min(distances, axis=2)[:, np.newaxis]) ** (2 / (m - 1))
```
3. 可以使用numpy的einsum函数进一步优化计算距离矩阵的过程:
```
distances = np.sqrt(np.einsum('ijk->ij', (X[:, np.newaxis, :] - centroids) ** 2))
```
4. 可以将一些常数值(如2和1)提前计算并存储,避免重复计算:
```
c1 = 2 / (m - 1)
c2 = 1 / (m - 1)
U_new = 1 / (distances / np.min(distances, axis=2)[:, np.newaxis]) ** c1
```
综上,以下是优化后的代码:
```
import numpy as np
from numpy.linalg import norm
def fcm(X, c, m, error=0.0001, maxiter=1000):
# 初始化隶属度矩阵 U
U = np.random.rand(c, X.shape[0])
U /= np.sum(U, axis=0)
# 计算常数值
c1 = 2 / (m - 1)
c2 = 1 / (m - 1)
# 迭代计算
for i in range(maxiter):
# 计算聚类中心
centroids = U.dot(X) / U.sum(axis=1)[:, None]
# 计算距离矩阵
distances = np.sqrt(np.einsum('ijk->ij', (X[:, np.newaxis, :] - centroids) ** 2))
# 更新隶属度矩阵 U
U_new = 1 / (distances / np.min(distances, axis=2)[:, np.newaxis]) ** c1
U_new /= np.sum(U_new, axis=0)
# 判断收敛
if norm(U_new - U) < error:
break
U = U_new
# 返回聚类结果
return centroids, U.argmax(axis=0)
# 示例数据
X = np.random.rand(100, 2)
# 聚类数目
c = 3
# 模糊指数
m = 2
# 聚类
centroids, labels = fcm(X, c, m)
# 打印聚类中心和标签
print('Centroids:', centroids)
print('Labels:', labels)
```
阅读全文