日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

利用Inception-V3训练的权重微调,实现猫狗分类(基于keras)

發布時間:2024/7/23 63 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用Inception-V3训练的权重微调,实现猫狗分类(基于keras) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

利用Inception-V3訓練的權重微調實現貓狗的分類,其中權重的下載在我的博客下載資源處,https://download.csdn.net/download/fanzonghao/10566634

第一種權重不改變直接用mixed7層(mixed7呆會把打印結果一放就知道了)進行特征提取,然后在拉平,連上兩層神經網絡

def define_model():InceptionV3_weight_path='./model_weight/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'pre_trained_model=InceptionV3(input_shape=(150,150,3),include_top=False,#不包含全連接層weights=None)pre_trained_model.load_weights(InceptionV3_weight_path)#下面兩種取其一#僅僅用其做特征提取 不需要更新權值for layer in pre_trained_model.layers:print(layer.name)layer.trainable=False#微調權值# unfreeze=False# for layer in pre_trained_model.layers:# if unfreeze:# layer.trainable=True# if layer.name=='mixed6':# unfreeze=Truelast_layer=pre_trained_model.get_layer('mixed7')print(last_layer.output_shape)last_output=last_layer.output#以下是在模型的基礎上增加的x=layers.Flatten()(last_output)x=layers.Dense(1024,activation='relu')(x)x=layers.Dropout(0.2)(x)x=layers.Dense(1,activation='sigmoid')(x)model=Model(inputs=pre_trained_model.input,outputs=x)return model

第一種完全利用Inception-V3訓練的權重代碼

import os import tensorflow as tf import matplotlib.pyplot as pltfrom keras.applications.inception_v3 import InceptionV3 from keras import layers from keras.models import Model from keras.optimizers import RMSprop from keras import backend as K from keras.preprocessing.image import ImageDataGenerator import data_read """ #獲得所需求的圖片--進行了圖像增強 """ def data_deal_overfit():# 獲取數據的路徑train_dir, validation_dir, next_cat_pix, next_dog_pix = data_read.read_data()#圖像增強train_datagen=ImageDataGenerator(rescale=1./255,rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')test_datagen=ImageDataGenerator(rescale=1./255)#從文件夾獲取所需要求的圖片train_generator=train_datagen.flow_from_directory(train_dir,target_size=(150,150),batch_size=20,class_mode='binary')test_generator = test_datagen.flow_from_directory(validation_dir,target_size=(150, 150),batch_size=20,class_mode='binary')return train_generator,test_generator """ #定義模型并加入了dropout """ def define_model():InceptionV3_weight_path='./model_weight/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'pre_trained_model=InceptionV3(input_shape=(150,150,3),include_top=False,#不包含全連接層weights=None)pre_trained_model.load_weights(InceptionV3_weight_path)#下面兩種取其一#僅僅用其做特征提取 不需要更新權值for layer in pre_trained_model.layers:print(layer.name)layer.trainable=False#微調權值# unfreeze=False# for layer in pre_trained_model.layers:# if unfreeze:# layer.trainable=True# if layer.name=='mixed6':# unfreeze=Truelast_layer=pre_trained_model.get_layer('mixed7')print(last_layer.output_shape)last_output=last_layer.output#以下實在模型的基礎上增加的x=layers.Flatten()(last_output)x=layers.Dense(1024,activation='relu')(x)x=layers.Dropout(0.2)(x)x=layers.Dense(1,activation='sigmoid')(x)model=Model(inputs=pre_trained_model.input,outputs=x)return model""" 訓練模型 """ def train_model():model=define_model()model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])train_generator, test_generator = data_deal_overfit()# verbose:日志顯示,0為不在標準輸出流輸出日志信息,1為輸出進度條記錄,2為每個epoch輸出一行記錄# 訓練模型 返回history包含各種精度和損失history = model.fit_generator(train_generator,steps_per_epoch=100, # 2000 images=batch_szie*stepsepochs=50,validation_data=test_generator,validation_steps=50, # 1000=20*50verbose=2)#精度acc=history.history['acc']val_acc=history.history['val_acc']#損失loss=history.history['loss']val_loss=history.history['val_loss']#epochs的數量epochs=range(len(acc))plt.plot(epochs,acc)plt.plot(epochs, val_acc)plt.title('training and validation accuracy')plt.figure()plt.plot(epochs, loss)plt.plot(epochs, val_loss)plt.title('training and validation loss')plt.show()if __name__ == '__main__':train_model() 打印結果:其中這些代表每一層的名字,直接利用mixed7的特征,(none,7,7,768)就是該層的shape, 直接拉平,添加兩層神經網絡進行分類。

打印結果:這是每一層的名字,mixed7層的shape是(None,7,7,768)第一種做法就是直接利用該層及之前層的權重進行訓練分類的。

第二種:進行微調要不是需要對整個權重都進行重新賦值,因為前面層數學習到的特征是一些簡單的特征,只是隨著層數增強才更加具有針對性,故把mixed7層的卷積層權重 重新訓練,代碼:

unfreeze=False for layer in pre_trained_model.layers:if unfreeze:layer.trainable=Trueif layer.name=='mixed6':unfreeze=True

也就是把我上段完整的代碼注釋替換一下即可。

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的利用Inception-V3训练的权重微调,实现猫狗分类(基于keras)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。