K-Means聚类是最常用的无监督机器学习算法之一。顾名思义,它可用于创建数据集群,从本质上将它们隔离。
目前,我们将做一个简单的示例,将文件夹中的图像进行分离,该文件夹既有猫也有狗的图像。并且将创建两个单独的文件夹(群集),我们将介绍如何自动确定K的最佳值。

猫和狗的图像数据集
第一,我们将从导入所需的库开始。
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import cv2
import os, glob, shutil
然后我们会从文件夹中的图像读取所有的图像并对其进行处理,以提取特征提取。我们将图像大小调整为224×224,以匹配模型输入层的大小以进行特征提取。
input_dir = 'pets'
glob_dir = input_dir + '/*.jpg'
images = [cv2.resize(cv2.imread(file), (224, 224)) for file in glob.glob(glob_dir)]
paths = [file for file in glob.glob(glob_dir)]
images = np.array(np.float32(images).reshape(len(images), -1)/255)
目前,我们将在MobileNetV2(传输学习)的协助下进行特征提取。当然我们可以使用ResNet50,InceptionV3等,但是MobileNetV2速度很快,而且资源也不是许多。
model = tf.keras.applications.MobileNetV2(include_top=False,
weights=’imagenet’, input_shape=(224, 224, 3))
predictions = model.predict(images.reshape(-1, 224, 224, 3))
pred_images = predictions.reshape(images.shape[0], -1)
目前,我们已经实现了提取功能,目前可以使用KMeans进行聚类了。
k = 2
kmodel = KMeans(n_clusters = k, n_jobs=-1, random_state=728)
kmodel.fit(pred_images)
kpredictions = kmodel.predict(pred_images)
shutil.rmtree(‘output’)
for i in range(k):
os.makedirs(“outputcluster” + str(i))
for i in range(len(paths)):
shutil.copy2(paths[i], “outputcluster”+str(kpredictions[i]))
输出结果如下:
小狗:

猫:

另外我们如何确定数据集的K值?我们可以使用轮廓法或肘部法确定它。我们将在这里使用轮廓法,当然这两种方法都可获得最可靠的结果,所以能直接确定K。
当我们将马的图像添加到原始数据聚焦时,我们来确定K的值。
sil = []
kl = []
kmax = 10
for k in range(2, kmax+1):
kmeans2 = KMeans(n_clusters = k).fit(pred_images)
labels = kmeans2.labels_
sil.append(silhouette_score(pred_images, labels, metric = ‘euclidean’))
kl.append(k)
目前,我们将绘制图像:
plt.plot(kl, sil)
plt.ylabel(‘Silhoutte Score’)
plt.ylabel(‘K’)
plt.show()

如我们所见,K的最佳值为3,我们还成功创建了第三个集群:

结论
如我们所见,K-Means聚类是用于图像分离的出色算法。在某些时候,我们使用的方法可能无法提供准确的结果,我们可以尝试使用其他卷积神经网络对其进行修复,或者尝试将图像从BGR转换为RGB,然后进行处理。
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END















暂无评论内容