訂閱
糾錯
加入自媒體

如何創(chuàng)建一個能夠區(qū)分或識別圖像的系統(tǒng)?

讓我們可視化來自橄欖球和足球的隨機圖像:plt.figure(figsize = (5,5))
plt.imshow(train[1][0])
plt.title(labels[train[0][1]])
輸出:

足球圖片也應用相同操作:plt.figure(figsize = (5,5))
plt.imshow(train[-1][0])
plt.title(labels[train[-1][1]])
輸出:

步驟4: 數(shù)據(jù)預處理和數(shù)據(jù)增強接下來,在繼續(xù)構(gòu)建模型之前,我們執(zhí)行一些數(shù)據(jù)預處理和數(shù)據(jù)增強。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)
對訓練數(shù)據(jù)的數(shù)據(jù)增強: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: 定義模型讓我們定義一個簡單的CNN模型,有3個卷積層,然后是max-pooling層。在第3次maxpool操作后添加一個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ù)來編譯模型。我們使用較低的學習率0.000001來獲得更平滑的曲線。opt = Adam(lr=0.000001)
model.compile(optimizer = opt , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])
現(xiàn)在,讓我們訓練我們的模型500個epochs,因為我們的學習速率非常小。history = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))
步驟6: 評估結(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()
讓我們看看曲線是怎樣的-

我們可以打印出分類報告,看看精度和準確性。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模型能夠達到83%的準確率。通過一些超參數(shù)調(diào)整,我們或許可以提高2-3%的精度。我們還可以將一些預測錯誤的圖像可視化,看看我們的分類器哪里出錯了。遷移學習的藝術(shù)我們先來看看遷移學習是什么。遷移學習是一種機器學習技術(shù),在一個任務上訓練的模型被重新用于第二個相關(guān)的任務。遷移學習的另一個關(guān)鍵應用是當數(shù)據(jù)集很小的時候,通過在相似的圖像上使用預先訓練過的模型,我們可以很容易地提高性能。既然我們的問題陳述很適合遷移學習,那么讓我們看看我們可以如何執(zhí)行一個預先訓練好的模型,以及我們能夠達到什么樣的精度。步驟1: 導入模型我們將從MobileNetV2模型創(chuàng)建一個基本模型。這是在ImageNet數(shù)據(jù)集上預先訓練的,ImageNet數(shù)據(jù)集是一個包含1.4M圖像和1000個類的大型數(shù)據(jù)集。這個知識庫將幫助我們從特定數(shù)據(jù)集中對橄欖球和足球進行分類。通過指定參數(shù) include_top=False,可以加載一個不包含頂部分類層的網(wǎng)絡(luò)。base_model = tf.keras.a(chǎn)pplications.MobileNetV2(input_shape = (224, 224, 3), include_top = False, weights = "imagenet")
在編譯和訓練模型之前凍結(jié)基礎(chǔ)模型是很重要的。凍結(jié)后將防止我們的基礎(chǔ)模型中的權(quán)重在訓練期間被更新。base_model.trainable = False

接下來,我們使用base_model定義模型,然后使用GlobalAveragePooling函數(shù)將每個圖像的特征轉(zhuǎn)換為單個矢量。我們添加0.2的dropout和最終的全連接層,有2個神經(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")                                    
                               ])
接下來,讓我們編譯模型并開始訓練它。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()
讓我們看看曲線是怎樣的-

我們也打印一下分類報告,以便得到更詳細的結(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)']))

我們可以看到,通過遷移學習,我們可以得到更好的結(jié)果。橄欖球和足球的精度都高于我們的CNN模型,而且總體精度達到了91%,這對于這樣一個小數(shù)據(jù)集來說是非常好的。通過一些超參數(shù)調(diào)優(yōu)和更改參數(shù),我們也可以獲得更好的性能!下一步是什么?這只是計算機視覺領(lǐng)域的起點。事實上,試著改進你的基礎(chǔ)CNN模型來匹配或超過基準性能。你可以從VGG16等的架構(gòu)中學習超參數(shù)調(diào)優(yōu)的一些線索。你可以使用相同的ImageDataGenerator來增強圖像并增加數(shù)據(jù)集的大小。此外,你還可以嘗試實現(xiàn)更新和更好的架構(gòu),如DenseNet和XceptionNet。你也可以移動到其他的計算機視覺任務,如目標檢測和分割,你將意識到這些任務也可以簡化為圖像分類。尾注祝賀你已經(jīng)學習了如何創(chuàng)建自己的數(shù)據(jù)集、創(chuàng)建CNN模型或執(zhí)行遷移學習來解決問題。我們在這篇文章中學到了很多,從學習尋找圖像數(shù)據(jù)到創(chuàng)建能夠?qū)崿F(xiàn)合理性能的簡單CNN模型。我們還學習了遷移學習的應用,進一步提高了我們的績效。這還沒有結(jié)束,我們看到我們的模型錯誤分類了很多圖像,這意味著仍然有改進的空間。我們可以從尋找更多的數(shù)據(jù)開始,甚至實現(xiàn)更好的、最新的架構(gòu),以便更好地識別特性。

<上一頁  1  2  
聲明: 本文由入駐維科號的作者撰寫,觀點僅代表作者本人,不代表OFweek立場。如有侵權(quán)或其他問題,請聯(lián)系舉報。

發(fā)表評論

0條評論,0人參與

請輸入評論內(nèi)容...

請輸入評論/評論長度6~500個字

您提交的評論過于頻繁,請輸入驗證碼繼續(xù)

暫無評論

暫無評論

人工智能 獵頭職位 更多
掃碼關(guān)注公眾號
OFweek人工智能網(wǎng)
獲取更多精彩內(nèi)容
文章糾錯
x
*文字標題:
*糾錯內(nèi)容:
聯(lián)系郵箱:
*驗 證 碼:

粵公網(wǎng)安備 44030502002758號