使用python实现可以返回SSE的wkmeans
时间: 2024-01-01 11:06:44 浏览: 193
好的,以下是一个基于Python实现的可以返回SSE的wkmeans代码:
```python
import numpy as np
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
class WKMeans:
def __init__(self, k=2, max_iters=100, plot_steps=False):
self.k = k
self.max_iters = max_iters
self.plot_steps = plot_steps
# list of sample indices for each cluster
self.clusters = [[] for _ in range(self.k)]
# mean feature vector for each cluster
self.centroids = []
# SSE (sum of squared errors) for each iteration
self.sse = []
def predict(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# initialize centroids
random_sample_idxs = np.random.choice(self.n_samples, self.k, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
# optimization loop
for i in range(self.max_iters):
# update clusters
self.clusters = self._create_clusters(self.centroids)
if self.plot_steps:
self.plot()
# update centroids
centroids_old = self.centroids
self.centroids = self._get_centroids(self.clusters)
# check if converged
if self._is_converged(centroids_old, self.centroids):
break
# calculate SSE
self.sse.append(self._get_sse())
return self._get_cluster_labels(self.clusters)
def _get_cluster_labels(self, clusters):
labels = np.empty(self.n_samples)
for cluster_idx, cluster in enumerate(clusters):
for sample_idx in cluster:
labels[sample_idx] = cluster_idx
return labels
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.k)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def _closest_centroid(self, sample, centroids):
distances = [euclidean_distance(sample, point) for point in centroids]
closest_idx = np.argmin(distances)
return closest_idx
def _get_centroids(self, clusters):
centroids = np.zeros((self.k, self.n_features))
for cluster_idx, cluster in enumerate(clusters):
cluster_mean = np.mean(self.X[cluster], axis=0)
centroids[cluster_idx] = cluster_mean
return centroids
def _is_converged(self, centroids_old, centroids):
distances = [euclidean_distance(centroids_old[i], centroids[i]) for i in range(self.k)]
return sum(distances) == 0
def _get_sse(self):
sse = 0
for cluster_idx, cluster in enumerate(self.clusters):
for sample_idx in cluster:
sse += euclidean_distance(self.X[sample_idx], self.centroids[cluster_idx])
return sse
```
该代码使用numpy进行向量运算和计算欧几里得距离。初始化KMeans对象时可以指定聚类数目k、最大迭代次数max_iters和是否绘制迭代过程中每个簇的样本点分布(plot_steps),在调用predict方法时将数据集X传入进行聚类并返回每个样本点所属簇的标签。最后可以通过KMeans对象的sse属性获取每次迭代后的SSE值。
阅读全文