如何創(chuàng)建一個(gè)能夠區(qū)分或識別圖像的系統(tǒng)?
讓我們可視化來自橄欖球和足球的隨機(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)接下來,在繼續(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)
對訓(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è)簡單的CNN模型,有3個(gè)卷積層,然后是max-pooling層。在第3次maxpool操作后添加一個(gè)dropout層,以避免過度擬合。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ù)來編譯模型。我們使用較低的學(xué)習(xí)率0.000001來獲得更平滑的曲線。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: 評估結(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)']))
我們可以看到,我們簡單的CNN模型能夠達(dá)到83%的準(zhǔn)確率。通過一些超參數(shù)調(diào)整,我們或許可以提高2-3%的精度。我們還可以將一些預(yù)測錯(cuò)誤的圖像可視化,看看我們的分類器哪里出錯(cuò)了。遷移學(xué)習(xí)的藝術(shù)我們先來看看遷移學(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í)候,通過在相似的圖像上使用預(yù)先訓(xù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ù)據(jù)集中對橄欖球和足球進(jìn)行分類。通過指定參數(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
接下來,我們使用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")
])
接下來,讓我們編譯模型并開始訓(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: 評估結(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)']))
我們可以看到,通過遷移學(xué)習(xí),我們可以得到更好的結(jié)果。橄欖球和足球的精度都高于我們的CNN模型,而且總體精度達(dá)到了91%,這對于這樣一個(gè)小數(shù)據(jù)集來說是非常好的。通過一些超參數(shù)調(diào)優(yōu)和更改參數(shù),我們也可以獲得更好的性能!下一步是什么?這只是計(jì)算機(jī)視覺領(lǐng)域的起點(diǎn)。事實(shí)上,試著改進(jìn)你的基礎(chǔ)CNN模型來匹配或超過基準(zhǔn)性能。你可以從VGG16等的架構(gòu)中學(xué)習(xí)超參數(shù)調(diào)優(yōu)的一些線索。你可以使用相同的ImageDataGenerator來增強(qiáng)圖像并增加數(shù)據(jù)集的大小。此外,你還可以嘗試實(shí)現(xiàn)更新和更好的架構(gòu),如DenseNet和XceptionNet。你也可以移動(dòng)到其他的計(jì)算機(jī)視覺任務(wù),如目標(biāo)檢測和分割,你將意識到這些任務(wù)也可以簡化為圖像分類。尾注祝賀你已經(jīng)學(xué)習(xí)了如何創(chuàng)建自己的數(shù)據(jù)集、創(chuàng)建CNN模型或執(zhí)行遷移學(xué)習(xí)來解決問題。我們在這篇文章中學(xué)到了很多,從學(xué)習(xí)尋找圖像數(shù)據(jù)到創(chuàng)建能夠?qū)崿F(xiàn)合理性能的簡單CNN模型。我們還學(xué)習(xí)了遷移學(xué)習(xí)的應(yīng)用,進(jìn)一步提高了我們的績效。這還沒有結(jié)束,我們看到我們的模型錯(cuò)誤分類了很多圖像,這意味著仍然有改進(jìn)的空間。我們可以從尋找更多的數(shù)據(jù)開始,甚至實(shí)現(xiàn)更好的、最新的架構(gòu),以便更好地識別特性。

請輸入評論內(nèi)容...
請輸入評論/評論長度6~500個(gè)字
最新活動(dòng)更多
-
3月27日立即報(bào)名>> 【工程師系列】汽車電子技術(shù)在線大會(huì)
-
4月30日立即下載>> 【村田汽車】汽車E/E架構(gòu)革新中,新智能座艙挑戰(zhàn)的解決方案
-
5月15-17日立即預(yù)約>> 【線下巡回】2025年STM32峰會(huì)
-
即日-5.15立即報(bào)名>>> 【在線會(huì)議】安森美Hyperlux™ ID系列引領(lǐng)iToF技術(shù)革新
-
5月15日立即下載>> 【白皮書】精確和高效地表征3000V/20A功率器件應(yīng)用指南
-
5月16日立即參評 >> 【評選啟動(dòng)】維科杯·OFweek 2025(第十屆)人工智能行業(yè)年度評選
推薦專題
- 1 UALink規(guī)范發(fā)布:挑戰(zhàn)英偉達(dá)AI統(tǒng)治的開始
- 2 北電數(shù)智主辦酒仙橋論壇,探索AI產(chǎn)業(yè)發(fā)展新路徑
- 3 降薪、加班、裁員三重暴擊,“AI四小龍”已折戟兩家
- 4 “AI寒武紀(jì)”爆發(fā)至今,五類新物種登上歷史舞臺
- 5 國產(chǎn)智駕迎戰(zhàn)特斯拉FSD,AI含量差幾何?
- 6 光計(jì)算迎來商業(yè)化突破,但落地仍需時(shí)間
- 7 東陽光:2024年扭虧、一季度凈利大增,液冷疊加具身智能打開成長空間
- 8 地平線自動(dòng)駕駛方案解讀
- 9 封殺AI“照騙”,“淘寶們”終于不忍了?
- 10 優(yōu)必選:營收大增主靠小件,虧損繼續(xù)又逢關(guān)稅,能否乘機(jī)器人東風(fēng)翻身?