如何構(gòu)建一個(gè) CNN 模型,以從圖像中對(duì)幼苗的種類進(jìn)行分類?
將 CNN 擬合到數(shù)據(jù)上
接下來(lái)是將 CNN 模型擬合到我們的數(shù)據(jù)集上,這樣模型將從訓(xùn)練數(shù)據(jù)集中學(xué)習(xí)并更新權(quán)重。這個(gè)經(jīng)過(guò)訓(xùn)練的 CNN 模型可以進(jìn)一步用于獲得對(duì)我們測(cè)試數(shù)據(jù)集的最終預(yù)測(cè)。我們必須遵循一些先決條件,例如降低學(xué)習(xí)率、找到模型的最佳權(quán)重并保存這些計(jì)算出的權(quán)重,以便我們可以進(jìn)一步使用它們進(jìn)行測(cè)試和獲得預(yù)測(cè)。
根據(jù)我們的常識(shí),我們需要以下內(nèi)容
模型的最佳權(quán)重
降低學(xué)習(xí)率
保存模型的最后權(quán)重
lrr = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.4,
min_lr=0.00001)
filepath="drive/DataScience/PlantReco/weights.best_{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoints = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True, mode='max')
filepath="drive/DataScience/PlantReco/weights.last_auto4.hdf5"
checkpoints_full = ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=False, mode='max')
callbacks_list = [checkpoints, lrr, checkpoints_full]
#MODEL
# hist = model.fit_generator(datagen.flow(trainX, trainY, batch_size=75),
# epochs=35, validation_data=(testX, testY),
# steps_per_epoch=trainX.shape[0], callbacks=callbacks_list)
# LOADING MODEL
model.load_weights("../input/plantrecomodels/weights.best_17-0.96.hdf5")
dataset = np.load("../input/plantrecomodels/Data.npz")
data = dict(zip(("x_train","x_test","y_train", "y_test"), (dataset[k] for k in dataset)))
x_train = data['x_train']
x_test = data['x_test']
y_train = data['y_train']
y_test = data['y_test']
print(model.evaluate(x_train, y_train)) # Evaluate on train set
print(model.evaluate(x_test, y_test)) # Evaluate on test set
混淆矩陣
混淆矩陣是一種檢查我們的模型如何處理數(shù)據(jù)的方法。這是分析模型錯(cuò)誤的好方法。檢查以下代碼以獲取混淆矩陣
# PREDICTIONS
y_pred = model.predict(x_test)
y_class = np.a(chǎn)rgmax(y_pred, axis = 1)
y_check = np.a(chǎn)rgmax(y_test, axis = 1)
cmatrix = confusion_matrix(y_check, y_class)
print(cmatrix)
獲得預(yù)測(cè)
在最后一部分,我們將獲得對(duì)測(cè)試數(shù)據(jù)集的預(yù)測(cè)。
檢查以下代碼以使用經(jīng)過(guò)訓(xùn)練的模型獲取預(yù)測(cè)
path_to_test = '../input/plant-seedlings-classification/test.png'
pics = glob(path_to_test)
testimages = []
tests = []
count=1
num = len(pics)
for i in pics:
print(str(count)+'/'+str(num),end='r')
tests.a(chǎn)ppend(i.split('/')[-1])
testimages.a(chǎn)ppend(cv2.resize(cv2.imread(i),(scale,scale)))
count = count + 1
testimages = np.a(chǎn)sarray(testimages)
newtestimages = []
sets = []
getEx = True
for i in testimages:
blurr = cv2.GaussianBlur(i,(5,5),0)
hsv = cv2.cvtColor(blurr,cv2.COLOR_BGR2HSV)
lower = (25,40,50)
upper = (75,255,255)
mask = cv2.inRange(hsv,lower,upper)
struc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11))
mask = cv2.morphologyEx(mask,cv2.MORPH_CLOSE,struc)
boolean = mask>0
masking = np.zeros_like(i,np.uint8)
masking[boolean] = i[boolean]
newtestimages.a(chǎn)ppend(masking)
if getEx:
plt.subplot(2,3,1);plt.imshow(i)
plt.subplot(2,3,2);plt.imshow(blurr)
plt.subplot(2,3,3);plt.imshow(hsv)
plt.subplot(2,3,4);plt.imshow(mask)
plt.subplot(2,3,5);plt.imshow(boolean)
plt.subplot(2,3,6);plt.imshow(masking)
plt.show()
getEx=False
newtestimages = np.a(chǎn)sarray(newtestimages)
# OTHER MASKED IMAGES
for i in range(6):
plt.subplot(2,3,i+1)
plt.imshow(newtestimages[i])
Newtestimages=newtestimages/255
prediction = model.predict(newtestimages)
# PREDICTION TO A CSV FILE
pred = np.a(chǎn)rgmax(prediction,axis=1)
predStr = labels.classes_[pred]
result = {'file':tests,'species':predStr}
result = pd.DataFrame(result)
result.to_csv("Prediction.csv",index=False)、
尾注
所以在本文中,我們?cè)敿?xì)討論了使用 CNN進(jìn)行植物幼苗分類。希望你能從文中學(xué)到一些東西,它會(huì)在未來(lái)對(duì)你有所幫助。

發(fā)表評(píng)論
請(qǐng)輸入評(píng)論內(nèi)容...
請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字
圖片新聞
-
機(jī)器人奧運(yùn)會(huì)戰(zhàn)報(bào):宇樹機(jī)器人摘下首金,天工Ultra搶走首位“百米飛人”
-
存儲(chǔ)圈掐架!江波龍起訴佰維,索賠121萬(wàn)
-
長(zhǎng)安汽車母公司突然更名:從“中國(guó)長(zhǎng)安”到“辰致科技”
-
豆包前負(fù)責(zé)人喬木出軌BP后續(xù):均被辭退
-
字節(jié)AI Lab負(fù)責(zé)人李航卸任后返聘,Seed進(jìn)入調(diào)整期
-
員工持股爆雷?廣汽埃安緊急回應(yīng)
-
中國(guó)“智造”背后的「關(guān)鍵力量」
-
小米汽車研發(fā)中心重磅落地,寶馬家門口“搶人”
最新活動(dòng)更多
-
即日-9.16點(diǎn)擊進(jìn)入 >> 【限時(shí)福利】TE 2025國(guó)際物聯(lián)網(wǎng)展·深圳站
-
10月23日火熱報(bào)名中>> 2025是德科技創(chuàng)新技術(shù)峰會(huì)
-
10月23日立即報(bào)名>> Works With 開發(fā)者大會(huì)深圳站
-
10月24日立即參評(píng)>> 【評(píng)選】維科杯·OFweek 2025(第十屆)物聯(lián)網(wǎng)行業(yè)年度評(píng)選
-
11月27日立即報(bào)名>> 【工程師系列】汽車電子技術(shù)在線大會(huì)
-
12月18日立即報(bào)名>> 【線下會(huì)議】OFweek 2025(第十屆)物聯(lián)網(wǎng)產(chǎn)業(yè)大會(huì)
推薦專題
- 1 先進(jìn)算力新選擇 | 2025華為算力場(chǎng)景發(fā)布會(huì)暨北京xPN伙伴大會(huì)成功舉辦
- 2 人形機(jī)器人,正狂奔在批量交付的曠野
- 3 宇樹機(jī)器人撞人事件的深度剖析:六維力傳感器如何成為人機(jī)安全的關(guān)鍵屏障
- 4 解碼特斯拉新AI芯片戰(zhàn)略 :從Dojo到AI5和AI6推理引擎
- 5 AI版“四萬(wàn)億刺激”計(jì)劃來(lái)了
- 6 騰訊 Q2 財(cái)報(bào)亮眼:AI 已成第二增長(zhǎng)曲線
- 7 2025年8月人工智能投融資觀察
- 8 9 a16z最新AI百?gòu)?qiáng)榜:硅谷頂級(jí)VC帶你讀懂全球生成式AI賽道最新趨勢(shì)
- 10 Manus跑路,大廠掉線,只能靠DeepSeek了