如何創(chuàng)建一個(gè)能夠區(qū)分或識(shí)別圖像的系統(tǒng)?
讓我們可視化來(lái)自橄欖球和足球的隨機(jī)圖像:plt.figure(figsize = (5,5))
plt.imshow(train[1][0])
plt.title(labels[train[0][1]])
輸出:
足球圖片也應(yīng)用相同操作:plt.figure(figsize = (5,5))
plt.imshow(train[-1][0])
plt.title(labels[train[-1][1]])
輸出:
步驟4: 數(shù)據(jù)預(yù)處理和數(shù)據(jù)增強(qiáng)接下來(lái),在繼續(xù)構(gòu)建模型之前,我們執(zhí)行一些數(shù)據(jù)預(yù)處理和數(shù)據(jù)增強(qiáng)。x_train = []
y_train = []
x_val = []
y_val = []
for feature, label in train:
x_train.a(chǎn)ppend(feature)
y_train.a(chǎn)ppend(label)
for feature, label in val:
x_val.a(chǎn)ppend(feature)
y_val.a(chǎn)ppend(label)
# Normalize the data
x_train = np.a(chǎn)rray(x_train) / 255
x_val = np.a(chǎn)rray(x_val) / 255
x_train.reshape(-1, img_size, img_size, 1)
y_train = np.a(chǎn)rray(y_train)
x_val.reshape(-1, img_size, img_size, 1)
y_val = np.a(chǎn)rray(y_val)
對(duì)訓(xùn)練數(shù)據(jù)的數(shù)據(jù)增強(qiáng):datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range = 30, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.2, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip = True, # randomly flip images
vertical_flip=False) # randomly flip images
datagen.fit(x_train)
步驟5: 定義模型讓我們定義一個(gè)簡(jiǎn)單的CNN模型,有3個(gè)卷積層,然后是max-pooling層。在第3次maxpool操作后添加一個(gè)dropout層,以避免過(guò)度擬合。model = Sequential()
model.a(chǎn)dd(Conv2D(32,3,padding="same", activation="relu", input_shape=(224,224,3)))
model.a(chǎn)dd(MaxPool2D())
model.a(chǎn)dd(Conv2D(32, 3, padding="same", activation="relu"))
model.a(chǎn)dd(MaxPool2D())
model.a(chǎn)dd(Conv2D(64, 3, padding="same", activation="relu"))
model.a(chǎn)dd(MaxPool2D())
model.a(chǎn)dd(Dropout(0.4))
model.a(chǎn)dd(Flatten())
model.a(chǎn)dd(Dense(128,activation="relu"))
model.a(chǎn)dd(Dense(2, activation="softmax"))
model.summary()
現(xiàn)在讓我們使用Adam作為優(yōu)化器,SparseCategoricalCrossentropy作為損失函數(shù)來(lái)編譯模型。我們使用較低的學(xué)習(xí)率0.000001來(lái)獲得更平滑的曲線。opt = Adam(lr=0.000001)
model.compile(optimizer = opt , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])
現(xiàn)在,讓我們訓(xùn)練我們的模型500個(gè)epochs,因?yàn)槲覀兊膶W(xué)習(xí)速率非常小。history = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))
步驟6: 評(píng)估結(jié)果我們將繪制我們的訓(xùn)練和驗(yàn)證的準(zhǔn)確性以及訓(xùn)練和驗(yàn)證的損失。acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(500)
plt.figure(figsize=(15, 15))
plt.subplot(2, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
讓我們看看曲線是怎樣的-
我們可以打印出分類報(bào)告,看看精度和準(zhǔn)確性。predictions = model.predict_classes(x_val)
predictions = predictions.reshape(1,-1)[0]
print(classification_report(y_val, predictions, target_names = ['Rugby (Class 0)','Soccer (Class 1)']))
我們可以看到,我們簡(jiǎn)單的CNN模型能夠達(dá)到83%的準(zhǔn)確率。通過(guò)一些超參數(shù)調(diào)整,我們或許可以提高2-3%的精度。我們還可以將一些預(yù)測(cè)錯(cuò)誤的圖像可視化,看看我們的分類器哪里出錯(cuò)了。遷移學(xué)習(xí)的藝術(shù)我們先來(lái)看看遷移學(xué)習(xí)是什么。遷移學(xué)習(xí)是一種機(jī)器學(xué)習(xí)技術(shù),在一個(gè)任務(wù)上訓(xùn)練的模型被重新用于第二個(gè)相關(guān)的任務(wù)。遷移學(xué)習(xí)的另一個(gè)關(guān)鍵應(yīng)用是當(dāng)數(shù)據(jù)集很小的時(shí)候,通過(guò)在相似的圖像上使用預(yù)先訓(xùn)練過(guò)的模型,我們可以很容易地提高性能。既然我們的問(wèn)題陳述很適合遷移學(xué)習(xí),那么讓我們看看我們可以如何執(zhí)行一個(gè)預(yù)先訓(xùn)練好的模型,以及我們能夠達(dá)到什么樣的精度。步驟1: 導(dǎo)入模型我們將從MobileNetV2模型創(chuàng)建一個(gè)基本模型。這是在ImageNet數(shù)據(jù)集上預(yù)先訓(xùn)練的,ImageNet數(shù)據(jù)集是一個(gè)包含1.4M圖像和1000個(gè)類的大型數(shù)據(jù)集。這個(gè)知識(shí)庫(kù)將幫助我們從特定數(shù)據(jù)集中對(duì)橄欖球和足球進(jìn)行分類。通過(guò)指定參數(shù) include_top=False,可以加載一個(gè)不包含頂部分類層的網(wǎng)絡(luò)。base_model = tf.keras.a(chǎn)pplications.MobileNetV2(input_shape = (224, 224, 3), include_top = False, weights = "imagenet")
在編譯和訓(xùn)練模型之前凍結(jié)基礎(chǔ)模型是很重要的。凍結(jié)后將防止我們的基礎(chǔ)模型中的權(quán)重在訓(xùn)練期間被更新。base_model.trainable = False
接下來(lái),我們使用base_model定義模型,然后使用GlobalAveragePooling函數(shù)將每個(gè)圖像的特征轉(zhuǎn)換為單個(gè)矢量。我們添加0.2的dropout和最終的全連接層,有2個(gè)神經(jīng)元和softmax激活。model = tf.keras.Sequential([base_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(2, activation="softmax")
])
接下來(lái),讓我們編譯模型并開(kāi)始訓(xùn)練它。base_learning_rate = 0.00001
model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))
步驟2: 評(píng)估結(jié)果acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(500)
plt.figure(figsize=(15, 15))
plt.subplot(2, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
讓我們看看曲線是怎樣的-
我們也打印一下分類報(bào)告,以便得到更詳細(xì)的結(jié)果。predictions = model.predict_classes(x_val)
predictions = predictions.reshape(1,-1)[0]
print(classification_report(y_val, predictions, target_names = ['Rugby (Class 0)','Soccer (Class 1)']))
我們可以看到,通過(guò)遷移學(xué)習(xí),我們可以得到更好的結(jié)果。橄欖球和足球的精度都高于我們的CNN模型,而且總體精度達(dá)到了91%,這對(duì)于這樣一個(gè)小數(shù)據(jù)集來(lái)說(shuō)是非常好的。通過(guò)一些超參數(shù)調(diào)優(yōu)和更改參數(shù),我們也可以獲得更好的性能!下一步是什么?這只是計(jì)算機(jī)視覺(jué)領(lǐng)域的起點(diǎn)。事實(shí)上,試著改進(jìn)你的基礎(chǔ)CNN模型來(lái)匹配或超過(guò)基準(zhǔn)性能。你可以從VGG16等的架構(gòu)中學(xué)習(xí)超參數(shù)調(diào)優(yōu)的一些線索。你可以使用相同的ImageDataGenerator來(lái)增強(qiáng)圖像并增加數(shù)據(jù)集的大小。此外,你還可以嘗試實(shí)現(xiàn)更新和更好的架構(gòu),如DenseNet和XceptionNet。你也可以移動(dòng)到其他的計(jì)算機(jī)視覺(jué)任務(wù),如目標(biāo)檢測(cè)和分割,你將意識(shí)到這些任務(wù)也可以簡(jiǎn)化為圖像分類。尾注祝賀你已經(jīng)學(xué)習(xí)了如何創(chuàng)建自己的數(shù)據(jù)集、創(chuàng)建CNN模型或執(zhí)行遷移學(xué)習(xí)來(lái)解決問(wèn)題。我們?cè)谶@篇文章中學(xué)到了很多,從學(xué)習(xí)尋找圖像數(shù)據(jù)到創(chuàng)建能夠?qū)崿F(xiàn)合理性能的簡(jiǎn)單CNN模型。我們還學(xué)習(xí)了遷移學(xué)習(xí)的應(yīng)用,進(jìn)一步提高了我們的績(jī)效。這還沒(méi)有結(jié)束,我們看到我們的模型錯(cuò)誤分類了很多圖像,這意味著仍然有改進(jìn)的空間。我們可以從尋找更多的數(shù)據(jù)開(kāi)始,甚至實(shí)現(xiàn)更好的、最新的架構(gòu),以便更好地識(shí)別特性。

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