编程实现K-means算法针对UCI的waveform数据集中每类数据取100个;对一副无噪图像进行分割
时间: 2023-11-22 09:53:10 浏览: 103
以下是Python实现K-means算法的代码,其中包括对UCI的waveform数据集进行聚类和对一副无噪图像进行分割的示例。
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from skimage import io
# 载入UCI的waveform数据集
data = np.loadtxt('waveform.data', delimiter=',')
X = data[:, :-1]
y = data[:, -1]
# 取每类数据的前100个
indices = np.zeros(3, dtype=int)
for i in range(3):
indices[i] = np.where(y == i+1)[0][:100]
X_sampled = X[indices.flatten()]
# 使用K-means算法进行聚类
kmeans = KMeans(n_clusters=3, random_state=0).fit(X_sampled)
# 绘制聚类结果
fig, ax = plt.subplots()
colors = ['r', 'g', 'b']
for i, color in enumerate(colors):
ax.scatter(X_sampled[kmeans.labels_ == i, 0], X_sampled[kmeans.labels_ == i, 1], c=color, label=f'Class {i+1}')
ax.legend()
plt.show()
# 对一副无噪图像进行分割
img = io.imread('image.jpg')
height, width, _ = img.shape
X = np.reshape(img, (height*width, 3))
# 使用K-means算法进行聚类
kmeans = KMeans(n_clusters=4, random_state=0).fit(X)
# 将每个像素点的颜色替换为对应簇的中心颜色
X_clustered = np.zeros_like(X)
for i in range(4):
X_clustered[kmeans.labels_ == i] = kmeans.cluster_centers_[i]
img_clustered = np.reshape(X_clustered, (height, width, 3))
# 显示分割结果
fig, ax = plt.subplots(1, 2)
ax[0].imshow(img)
ax[1].imshow(img_clustered)
plt.show()
```
上述代码首先载入UCI的waveform数据集,并从中取每类数据的前100个进行聚类。然后使用K-means算法对一副无噪图像进行分割,将每个像素点的颜色替换为对应簇的中心颜色。最后绘制UCI的waveform数据集的聚类结果和一副无噪图像的分割结果。
可以根据自己的需要修改代码中的数据集路径、簇数等参数。