重磅干货,第一时间送达 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 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(“output\cluster” + str(i)) for i in range(len(paths)): shutil.copy2(paths[i], “output\cluster”+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,然后进行处理。 |
|