如何使用Python將給定的圖像集進(jìn)行聚類?
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..featureMaps'}, '*')">featureMaps = <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..model'}, '*')">model.predict(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..img'}, '*')">img)
## Plotting Features
for a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..maps'}, '*')">maps in <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..featureMaps'}, '*')">featureMaps:
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.figure'}, '*')">figure(figsize=(20,20))
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..pltNum'}, '*')">pltNum = 1
for <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..a(chǎn)'}, '*')">a in range(8):
for <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..b'}, '*')">b in <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..range'}, '*')">range(8):
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.subplot'}, '*')">subplot(8, 8, <a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..pltNum'}, '*')">pltNum)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.imshow'}, '*')">imshow(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..maps'}, '*')">maps[: ,: ,<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..pltNum'}, '*')">pltNum - 1], cmap='gray')
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.12234793.44545592.ShowMeWhatYouLearnt..pltNum'}, '*')">pltNum += 1
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.show'}, '*')">show()
接下來我們將重點(diǎn)介紹如何來創(chuàng)建我們的聚類算法。設(shè)計(jì)圖像聚類算法在本節(jié)中,我們使用Kaggle上的 keep-babies-safe 數(shù)據(jù)集。https://www.kaggle.com/akash14/keep-babies-safe首先,我們創(chuàng)建一個(gè)圖像聚類模型,來將給定的圖像分為兩類,即玩具或消費(fèi)品,以下是來自該數(shù)據(jù)集的一些圖像。
以下代碼實(shí)現(xiàn)我們的聚類算法:##################### Making Essential Imports ############################
import sklearn
import os
import sys
import matplotlib.pyplot as plt
import cv2
import pytesseract
import numpy as np
import pandas as pd
import tensorflow as tf
conf = r'-- oem 2'
#####################################
# Defining a skeleton for our #
# DataFrame #
#####################################
DataFrame = {
'photo_name' : [],
'flattenPhoto' : [],
'text' : [],
}
#######################################################################################
# The Approach is to apply transfer learning hence using Resnet50 as my #
# pretrained model #
#######################################################################################
MyModel = tf.keras.models.Sequential()
MyModel.a(chǎn)dd(tf.keras.a(chǎn)pplications.ResNet50(
include_top = False, weights='imagenet', pooling='avg',
))
# freezing weights for 1st layer
MyModel.layers[0].trainable = False
### Now defining dataloading Function
def LoadDataAndDoEssentials(path, h, w):
img = cv2.imread(path)
DataFrame['text'].a(chǎn)ppend(pytesseract.image_to_string(img, config = conf))
img = cv2.resize(img, (h, w))
## Expanding image dims so this represents 1 sample
img = img = np.expand_dims(img, 0)
img = tf.keras.a(chǎn)pplications.resnet50.preprocess_input(img)
extractedFeatures = MyModel.predict(img)
extractedFeatures = np.a(chǎn)rray(extractedFeatures)
DataFrame['flattenPhoto'].a(chǎn)ppend(extractedFeatures.flatten())
### with this all done lets write the iterrrative loop
def ReadAndStoreMyImages(path):
list_ = os.listdir(path)
for mem in list_:
DataFrame['photo_name'].a(chǎn)ppend(mem)
imagePath = path + '/' + mem
LoadDataAndDoEssentials(imagePath, 224, 224)
### lets give the address of our Parent directory and start
path = 'enter your data's path here'
ReadAndStoreMyImages(path)
######################################################
# lets now do clustering #
######################################################
Training_Feature_vector = np.a(chǎn)rray(DataFrame['flattenPhoto'], dtype = 'float64')
from sklearn.cluster import AgglomerativeClustering
kmeans = AgglomerativeClustering(n_clusters = 2)
kmeans.fit(Training_Feature_vector)
A little explanation for the above code:
上面的代碼使用Resnet50(一種經(jīng)過預(yù)先訓(xùn)練的CNN)進(jìn)行特征提取,我們只需移除其頭部或用于預(yù)測類別的神經(jīng)元的最后一層,然后將圖像輸入到CNN并獲得特征向量作為輸出,實(shí)際上,這是我們的CNN在Resnet50的倒數(shù)第二層學(xué)習(xí)到的所有特征圖的扁平數(shù)組?梢詫⒋溯敵鱿蛄刻峁┙o進(jìn)行圖像聚類的任何聚類算法。讓我向你展示通過這種方法創(chuàng)建的簇。
該可視化的代碼如下## lets make this a dataFrame
import seaborn as sb
import matplotlib.pyplot as plt
dimReducedDataFrame = pd.DataFrame(Training_Feature_vector)
dimReducedDataFrame = dimReducedDataFrame.rename(columns = { 0: 'V1', 1 : 'V2'})
dimReducedDataFrame['Category'] = list (df['Class_of_image'])
plt.figure(figsize = (10, 5))
sb.scatterplot(data = dimReducedDataFrame, x = 'V1', y = 'V2',hue = 'Category')
plt.grid(True)
plt.show()
結(jié)論本文通過解釋如何使用深度學(xué)習(xí)和聚類將視覺上相似的圖像聚在一起形成簇,而無需創(chuàng)建數(shù)據(jù)集并在其上訓(xùn)練CNN。

請輸入評論內(nèi)容...
請輸入評論/評論長度6~500個(gè)字
最新活動更多
-
6月20日立即下載>> 【白皮書】精準(zhǔn)測量 安全高效——福祿克光伏行業(yè)解決方案
-
7月3日立即報(bào)名>> 【在線會議】英飛凌新一代智能照明方案賦能綠色建筑與工業(yè)互聯(lián)
-
7月22-29日立即報(bào)名>> 【線下論壇】第三屆安富利汽車生態(tài)圈峰會
-
7.30-8.1火熱報(bào)名中>> 全數(shù)會2025(第六屆)機(jī)器人及智能工廠展
-
7月31日免費(fèi)預(yù)約>> OFweek 2025具身機(jī)器人動力電池技術(shù)應(yīng)用大會
-
免費(fèi)參會立即報(bào)名>> 7月30日- 8月1日 2025全數(shù)會工業(yè)芯片與傳感儀表展
推薦專題
- 1 AI 眼鏡讓百萬 APP「集體失業(yè)」?
- 2 大廠紛紛入局,百度、阿里、字節(jié)搶奪Agent話語權(quán)
- 3 深度報(bào)告|中國AI產(chǎn)業(yè)正在崛起成全球力量,市場潛力和關(guān)鍵挑戰(zhàn)有哪些?
- 4 上海跑出80億超級獨(dú)角獸:獲上市公司戰(zhàn)投,干人形機(jī)器人
- 5 一文看懂視覺語言動作模型(VLA)及其應(yīng)用
- 6 國家數(shù)據(jù)局局長劉烈宏調(diào)研格創(chuàng)東智
- 7 下一代入口之戰(zhàn):大廠為何紛紛押注智能體?
- 8 百億AI芯片訂單,瘋狂傾銷中東?
- 9 Robotaxi新消息密集釋放,量產(chǎn)元年誰在領(lǐng)跑?
- 10 格斗大賽出圈!人形機(jī)器人致命短板曝光:頭腦過于簡單