怎么使用keras識別狗的品種

這篇文章主要介紹“怎么使用keras識別狗的品種”,在日常操作中,相信很多人在怎么使用keras識別狗的品種問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用keras識別狗的品種”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

創(chuàng)新互聯(lián)是一家專業(yè)提供海城企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站制作、成都做網(wǎng)站、html5、小程序制作等業(yè)務(wù)。10年已為海城眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進行中。

數(shù)據(jù)分析

以下是關(guān)于數(shù)據(jù)的一些介紹:

  1. 犬種總數(shù):133

  2. 狗圖片總數(shù):8351(訓(xùn)練集:6680,驗證集:835,測試集:836)

  3. 最受歡迎的品種:阿拉斯加:96,博德牧羊犬:93

按圖片數(shù)量排序的前30個品種如下:

怎么使用keras識別狗的品種

我們還可以在這里看到一些狗的圖片和它們的品種:

怎么使用keras識別狗的品種


數(shù)據(jù)預(yù)處理

經(jīng)過分析,為機器學(xué)習(xí)算法準(zhǔn)備數(shù)據(jù)。我們將把每個圖像作為一個numpy數(shù)組加載,并將它們的大小調(diào)整為224x224,因為這是大多數(shù)傳統(tǒng)神經(jīng)網(wǎng)絡(luò)接受圖像的默認大小。我們還將為圖像的數(shù)量添加另一個維度

from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    '''將給定路徑下的圖像轉(zhuǎn)換為張量'''
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    '''將給定路徑中的所有圖像轉(zhuǎn)換為張量'''
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

最后,我們將使用ImageDataGenerator對圖像進行動態(tài)縮放和增強

train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255,
                                                horizontal_flip=True,
                                                vertical_flip=True,
                                                rotation_range=20)

valid_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255.)

test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255.)


train_generator = train_datagen.flow(train_tensors, train_targets, batch_size=32)
valid_generator = train_datagen.flow(valid_tensors, valid_targets, batch_size=32)
test_generator = train_datagen.flow(test_tensors, test_targets, batch_size=32)

CNN

我們將在預(yù)處理數(shù)據(jù)集上從頭開始訓(xùn)練卷積神經(jīng)網(wǎng)絡(luò)(CNN),如下所示:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(256, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(2048, activation='softmax'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(1024, activation='softmax'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(133, activation='softmax')
])


model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath='../saved_models/weights_best_custom.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_generator, epochs=5, validation_data=valid_generator, callbacks=[checkpointer])

我們使用一個ModelCheckpoint回調(diào)來保存基于驗證分數(shù)的模型。測試這個模型,我們得到的準(zhǔn)確率只有1%左右


使用遷移學(xué)習(xí)

現(xiàn)在,我們將看到如何使用預(yù)訓(xùn)練的特征可以產(chǎn)生巨大的不同。下載ResNet-50。你可以通過運行下面的代碼單元來提取相應(yīng)的訓(xùn)練集、測試和驗證集:

bottleneck_features = np.load('Data/bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']

我們現(xiàn)在將再次定義模型,并對提取的特征使用GlobalAveragePooling2D,它將一組特征平均為一個值。最后,如果驗證損失在兩個連續(xù)的epoch內(nèi)沒有增加,我們使用額外的回調(diào)來降低學(xué)習(xí)率,降低平臺,并且如果驗證損失在連續(xù)的5個epoch內(nèi)沒有增加,也可以提前停止訓(xùn)練。

Resnet50_model = tf.keras.models.Sequential()
Resnet50_model.add(tf.keras.layers.GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(tf.keras.layers.Dense(1024, activation='relu'))
Resnet50_model.add(tf.keras.layers.Dense(133, activation='softmax'))

Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath='saved_models/weights_best_Resnet50.hdf5', 
                               verbose=1, save_best_only=True)
early_stopping = tf.keras.callbacks.EarlyStopping(patience=5, monitor='val_loss')

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(patience=2, monitor='val_loss')
Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=50, batch_size=20, callbacks=[checkpointer, early_stopping, reduce_lr], verbose=1)### 訓(xùn)練模型

在測試集上的準(zhǔn)確率為82.65%。與我們白手起家訓(xùn)練的模型相比,這是一個巨大的進步。


構(gòu)建web應(yīng)用程序

對于web應(yīng)用程序,我們將首先編寫一個helper函數(shù),該函數(shù)接受圖像路徑并返回品種。label_to_cat字典將每個數(shù)字標(biāo)簽映射到它的狗品種。

def predict_breed(img_path):
    '''預(yù)測給定圖像的品種'''
    # 提取特征
    bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
    bottleneck_feature = tf.keras.models.Sequential([
                            tf.keras.layers.GlobalAveragePooling2D(input_shape=bottleneck_feature.shape[1:])
                        ]).predict(bottleneck_feature).reshape(1, 1, 1, 2048)
    # 獲得預(yù)測向量
    predicted_vector = Resnet50_model.predict(bottleneck_feature)
    # 模型預(yù)測的犬種
    return label_to_cat[np.argmax(predicted_vector)]

對于web應(yīng)用程序,我們將使用flaskweb框架來幫助我們用最少的代碼創(chuàng)建web應(yīng)用程序。我們將定義一個接受圖像的路由,并用狗的品種呈現(xiàn)一個輸出模板

@app.route('/upload', methods=['POST','GET'])
def upload_file():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        file = request.files['image']
        full_name = os.path.join(UPLOAD_FOLDER, file.filename)
        file.save(full_name)
        dog_breed = dog_breed_classifier(full_name)
    return render_template('predict.html', image_file_name = file.filename, label = dog_breed)

predict.html是分別顯示圖像及其犬種的模板。

到此,關(guān)于“怎么使用keras識別狗的品種”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

網(wǎng)頁題目:怎么使用keras識別狗的品種
本文URL:http://muchs.cn/article30/jcjdso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化外貿(mào)網(wǎng)站建設(shè)、企業(yè)建站網(wǎng)頁設(shè)計公司、、網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作