keras系列︱Application中五款已訓練模型、VGG16框架(Sequential式、Model式)解讀(二)...

引自:http://blog.csdn.net/sinat_26917383/article/details/72859145

中文文檔:http://keras-cn.readthedocs.io/en/latest/?
官方文檔:https://keras.io/?
文檔主要是以keras2.0。?
.


.

Keras系列:

1、keras系列︱Sequential與Model模型、keras基本結構功能(一)?
2、keras系列︱Application中五款已訓練模型、VGG16框架(Sequential式、Model式)解讀(二)?
3、keras系列︱圖像多分類訓練與利用bottleneck features進行微調(三)?
4、keras系列︱人臉表情分類與識別:opencv人臉檢測+Keras情緒分類(四)?
5、keras系列︱遷移學習:利用InceptionV3進行fine-tuning及預測、完整案例(五)


一、Application的五款已訓練模型 + H5py簡述

Kera的應用模塊Application提供了帶有預訓練權重的Keras模型,這些模型可以用來進行預測、特征提取和finetune。?
后續還有對以下幾個模型的參數介紹:

  • Xception
  • VGG16
  • VGG19
  • ResNet50
  • InceptionV3

所有的這些模型(除了Xception)都兼容Theano和Tensorflow,并會自動基于~/.keras/keras.json的Keras的圖像維度進行自動設置。例如,如果你設置data_format=”channel_last”,則加載的模型將按照TensorFlow的維度順序來構造,即“Width-Height-Depth”的順序。

模型的官方下載路徑:https://github.com/fchollet/deep-learning-models/releases

其中:?
.

1、thtf的區別

==================

Keras提供了兩套后端,Theano和Tensorflow,?
th和tf的大部分功能都被backend統一包裝起來了,但二者還是存在不小的沖突,有時候你需要特別注意Keras是運行在哪種后端之上,它們的主要沖突有:

dim_ordering,也就是維度順序。比方說一張224*224的彩色圖片,theano的維度順序是(3,224,224),即通道維在前。而tf的維度順序是(224,224,3),即通道維在后。?
卷積層權重的shape:從無到有訓練一個網絡,不會有任何問題。但是如果你想把一個th訓練出來的卷積層權重載入風格為tf的卷積層……說多了都是淚。我一直覺得這個是個bug,數據的dim_ordering有問題就罷了,為啥卷積層權重的shape還需要變換咧?我遲早要提個PR把這個bug修掉!?
然后是卷積層kernel的翻轉不翻轉問題,這個我們說過很多次了,就不再多提。?
數據格式的區別,channels_last”對應原本的“tf”,“channels_first”對應原本的“th”。?
以128x128的RGB圖像為例,“channels_first”應將數據組織為(3,128,128),而“channels_last”應將數據組織為(128,128,3)。?
譬如:?
vgg16_weights_th_dim_ordering_th_kernels_notop.h5?
vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5?
.

2、notop模型是指什么?

==============

是否包含最后的3個全連接層(whether to include the 3 fully-connected layers at the top of the network)。用來做fine-tuning專用,專門開源了這類模型。?
.

3、H5py簡述

========

keras的已訓練模型是H5PY格式的,不是caffe的.caffemodel?
h5py.File類似Python的詞典對象,因此我們可以查看所有的鍵值:?
讀入

file=h5py.File('.../notop.h5','r')
f.attrs['nb_layers'],代表f的屬性,其中有一個屬性為'nb_layers'

?

>>> f.keys()
[u'block1_conv1', u'block1_conv2', u'block1_pool', u'block2_conv1', u'block2_conv2', u'block2_pool', u'block3_conv1', u'block3_conv2', u'block3_conv3', u'block3_pool', u'block4_conv1', u'block4_conv2', u'block4_conv3', u'block4_pool', u'block5_conv1', u'block5_conv2', u'block5_conv3', u'block5_pool']

?

可以看到f中各個層內有些什么。

for name in f:print(name)# 類似f.keys()

.

4、官方案例——利用ResNet50網絡進行ImageNet分類

================================

rom keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as npmodel = ResNet50(weights='imagenet') img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds, top=3)[0]) # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]

還有的案例可見Keras官方文檔

利用VGG16提取特征、從VGG19的任意中間層中抽取特征、在定制的輸入tensor上構建InceptionV3

.

5、調用參數解釋

========

以下幾類,因為調用好像都是從網站下載權重,所以可以自己修改一下源碼,讓其可以讀取本地H5文件。

Xception模型

ImageNet上,該模型取得了驗證集top1 0.790和top5 0.945的正確率;?
,該模型目前僅能以TensorFlow為后端使用,由于它依賴于”SeparableConvolution”層,目前該模型只支持channels_last的維度順序(width, height, channels)

默認輸入圖片大小為299x299

keras.applications.xception.Xception(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None, classes=1000)

?

VGG16模型

VGG16模型,權重由ImageNet訓練而來

該模型再Theano和TensorFlow后端均可使用,并接受channels_first和channels_last兩種輸入維度順序

模型的默認輸入尺寸時224x224

keras.applications.vgg16.VGG16(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None, classes=1000)

VGG19模型

VGG19模型,權重由ImageNet訓練而來

該模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last兩種輸入維度順序

模型的默認輸入尺寸時224x224

keras.applications.vgg19.VGG19(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None, classes=1000)

?

ResNet50模型

50層殘差網絡模型,權重訓練自ImageNet

該模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last兩種輸入維度順序

模型的默認輸入尺寸時224x224

keras.applications.resnet50.ResNet50(include_top=True, weights='imagenet',input_tensor=None, input_shape=None,pooling=None, classes=1000)

InceptionV3模型

InceptionV3網絡,權重訓練自ImageNet

該模型在Theano和TensorFlow后端均可使用,并接受channels_first和channels_last兩種輸入維度順序

模型的默認輸入尺寸時299x299

keras.applications.inception_v3.InceptionV3(include_top=True,weights='imagenet',input_tensor=None,input_shape=None,pooling=None, classes=1000)

.


二、 keras-applications-VGG16解讀——函數式

.py文件來源于:https://github.com/fchollet/deep-learning-models/blob/master/vgg16.py?
VGG16默認的輸入數據格式應該是:channels_last

# -*- coding: utf-8 -*-
'''VGG16 model for Keras.
# Reference:
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
'''
from __future__ import print_functionimport numpy as np import warnings from keras.models import Model from keras.layers import Flatten from keras.layers import Dense from keras.layers import Input from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import GlobalMaxPooling2D from keras.layers import GlobalAveragePooling2D from keras.preprocessing import image from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras import backend as K from keras.applications.imagenet_utils import decode_predictions # decode_predictions 輸出5個最高概率:(類名, 語義概念, 預測概率) decode_predictions(y_pred) from keras.applications.imagenet_utils import preprocess_input # 預處理 圖像編碼服從規定,譬如,RGB,GBR這一類的,preprocess_input(x) from keras.applications.imagenet_utils import _obtain_input_shape # 確定適當的輸入形狀,相當于opencv中的read.img,將圖像變為數組 from keras.engine.topology import get_source_inputs WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5' WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5' def VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): # 檢查weight與分類設置是否正確 if weights not in {'imagenet', None}: raise ValueError('The `weights` argument should be either ' '`None` (random initialization) or `imagenet` ' '(pre-training on ImageNet).') if weights == 'imagenet' and include_top and classes != 1000: raise ValueError('If using `weights` as imagenet with `include_top`' ' as true, `classes` should be 1000') # 設置圖像尺寸,類似caffe中的transform # Determine proper input shape input_shape = _obtain_input_shape(input_shape, default_size=224, min_size=48, # 模型所能接受的最小長寬 data_format=K.image_data_format(), # 數據的使用格式 include_top=include_top) #是否通過一個Flatten層再連接到分類器 # 數據簡單處理,resize if input_tensor is None: img_input = Input(shape=input_shape) # 這里的Input是keras的格式,可以用于轉換 else: if not K.is_keras_tensor(input_tensor): img_input = Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor # 如果是tensor的數據格式,需要兩步走: # 先判斷是否是keras指定的數據類型,is_keras_tensor # 然后get_source_inputs(input_tensor) # 編寫網絡結構,prototxt # Block 1 x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input) x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x) # Block 2 x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x) x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x) # Block 3 x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x) x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x) x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x) # Block 4 x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x) # Block 5 x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x) x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x) if include_top: # Classification block x = Flatten(name='flatten')(x) x = Dense(4096, activation='relu', name='fc1')(x) x = Dense(4096, activation='relu', name='fc2')(x) x = Dense(classes, activation='softmax', name='predictions')(x) else: if pooling == 'avg': x = GlobalAveragePooling2D()(x) elif pooling == 'max': x = GlobalMaxPooling2D()(x) # 調整數據 # Ensure that the model takes into account # any potential predecessors of `input_tensor`. if input_tensor is not None: inputs = get_source_inputs(input_tensor) # get_source_inputs 返回計算需要的數據列表,List of input tensors. # 如果是tensor的數據格式,需要兩步走: # 先判斷是否是keras指定的數據類型,is_keras_tensor # 然后get_source_inputs(input_tensor) else: inputs = img_input # 創建模型 # Create model. model = Model(inputs, x, name='vgg16') # 加載權重 # load weights if weights == 'imagenet': if include_top: weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels.h5', WEIGHTS_PATH, cache_subdir='models') else: weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5', WEIGHTS_PATH_NO_TOP, cache_subdir='models') model.load_weights(weights_path) if K.backend() == 'theano': layer_utils.convert_all_kernels_in_model(model) if K.image_data_format() == 'channels_first': if include_top: maxpool = model.get_layer(name='block5_pool') shape = maxpool.output_shape[

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/284669.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/284669.shtml
英文地址,請注明出處:http://en.pswp.cn/news/284669.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【BIM入門實戰】Revit建筑墻體:構造、包絡、疊層圖文詳解

本文主要講解Revit建筑墻體:構造、包絡、疊層。 一、基本墻 第一步: 選擇菜單欄的【建筑】選項卡中的【墻】下拉菜單→【屬性】面板中切換至基本墻→點擊屬性面板中的【編輯類型】,彈出如下墻體對話框。 第二步: 選擇【復制】按鈕→重新進行編輯名稱,命名為“外墻-1F-2…

win11 恢復win10開始菜單及任務欄

Windows Registry Editor Version 5.00[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced] "Start_ShowClassicMode"dword:00000001 "TaskbarSi"dword:00000000將上述代碼存為reg文件,雙擊導入注冊表。 任務欄…

CentOS安裝Tomcat

1. 下載Tomcat安裝包: Tomcat官網 解壓下載下來的tar.gz至任意目錄下,執行命令: Java代碼 tar -xzf apache-tomcat-7.0.56.tar.gz 解壓后如圖: 如果是在windows上,則直接解壓zip包到任意目錄&…

【BIM+GIS】ArcGIS Pro2.8如何打開Revit模型,BIM和GIS融合?

ArcGIS Pro2.8中,可以直接打開Revit模型(.rvt)項目文件,實現了從數據格式方面BIM與GIS的有機融合,具體操作如下所示: 1. Revit2018模型繪制 打開Revit2018軟件,選擇【建筑樣板】,打開標高1樓層平面,新建一個簡單的戶型:包括四面墻體、2個門和一扇窗戶,如下圖所示。…

Edge 開發者沙龍|一小時精通Edge擴展開發

點擊藍字關注我們編輯:Alan Wang排版:Rani Sun微軟 Reactor 為幫助廣開發者,技術愛好者,更好的學習 .NET Core, C#, Python,數據科學,機器學習,AI,區塊鏈, IoT 等技術,將…

tomcat 開啟遠程debug

1、linux服務器上tomcat配置startup.sh 文件末尾添加(不換行):declare -x CATALINA_OPTS"-server -Xdebug -Xnoagent -Djava.compilerNONE -Xrunjdwp:transportdt_socket,servery,suspendn,address9876"2、eclipse配置:…

公歷還是很簡單的

1 import java.util.*;2 class CalendarTest3 {4 /*先輸出提示語句,并接受用戶輸入的年、月。5 根據用戶輸入的年,先判斷是否是閏年。6 根據用戶輸入的年份來判斷月的天數。7 用循環計算用戶輸入的年份距1900年1月1日的總天數。8 用…

【測繪程序設計】坐標反算神器V1.0(附C/C#/VB源程序)

【拓展閱讀】:【測繪程序設計】坐標正算神器V1.0(附C/C#/VB源程序) 一、坐標反算原理 ?坐標反算:已知兩點坐標,反求邊長和方位角,稱為坐標反算。 原理坐標系: 計算公式: 二、C#程序實現 1. 界面設計 2

在二維數組中查找一個數

在一個二維數組中,每一行都按照從左到右遞增的順序排列,每一列也按照從上到下遞增的順序排列。在這樣一個序列中查找一個數1 2 8 92 4 9 124 7 10 136 8 11 15例如查找7,就從第一行的最左邊查找,9大于7,則9以下的也不用…

ASP.NET Core 6框架揭秘實例演示[01]: 編程初體驗

本篇提供的20個簡單的演示實例基本涵蓋了ASP.NET Core 6基本的編程模式,我們不僅會利用它們來演示針對控制臺、API、MVC、gRPC應用的構建與編程,還會演示Dapr在.NET 6中的應用。除此之外,這20個實例還涵蓋了針對依賴注入、配置選項、日志記錄…

DBeaverEE 21.1.0安裝指南

1、 安裝jdk11 2、 配置環境變量 將jdk11安裝目錄加入path:C:\Program Files\Java\jdk-11.0.10\bin3、 安裝DBEE 21.1 4、 將dbeaver-agent文件夾復制到DBEE安裝目錄 5、將DBEE安裝目錄下的jre目錄刪除或改名 6、 修改dbeaver.ini文件,在文件最后添加…

跟風學Docker之四:Docker網絡解決方案

2019獨角獸企業重金招聘Python工程師標準>>> 跟風學Docker之四:Docker網絡解決方案 博客分類: docker 前言:前面的部分一直都是單機跑docker,但實際生產環境不可能只用一臺來跑。肯定會用到多臺,因為他們都…

C++中數字和字符的轉換

參考&#xff1a;http://blog.csdn.net/xw20084898/article/details/21939811 http://nnssll.blog.51cto.com/902724/198237/ http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html 一、stringstream通常是用來做數據轉換的。 1、例如int轉string:#include <s…

【測繪程序設計】坐標方位角推算神器(C#版)

本文講解利用C#語言實現坐標方位角推算,附源碼贈送。 1. 神器效果展示 (1)連接角為左角 (2)連接角為右角 2. 方位角推算原理速遞 (1)原理示意圖

原型模式——創建型模式

2019獨角獸企業重金招聘Python工程師標準>>> 思路&#xff1a; 馬上又到找工作的時候了&#xff0c;當我們在準備一份份簡歷的時候有沒有考慮過這樣一個問題&#xff1f; 面對不同的工作崗位我們需要準備不同的求職簡歷&#xff0c;但是這樣的幾份不同的簡歷中還是有…

如何獲取 ASP.NET Core 當前啟動地址?

前言上次&#xff0c;我們介紹了配置ASP.NET Core啟動地址的多種方法。那么&#xff0c;如何通過代碼方式&#xff0c;獲取啟動后的地址&#xff1f;WebApplication.Urls 對象使用 WebApplication.Urls.Add 方法可以添加啟動地址。那么&#xff0c;使用 WebApplication.Urls 應…

【CASS精品教程】CASS9.1查詢功能大全(坐標、長度、面積、方位角)

文章目錄 1. 查詢指定點坐標2. 查詢兩點距離及方位3. 查詢線長4. 查詢實體面積CASS9.1中提供了查詢指定點坐標、查詢兩點距離及方位、查詢線長、查詢實體面積等查詢功能,如下圖所示: 本文以動畫演示的方式,對以上提到的功能進行講解。 1. 查詢指定點坐標 點擊【工程應用】…

自定義smokeping告警(郵件+短信)

前段時間接到公司IT同事需求&#xff0c;幫助其配置smokeping的告警功能&#xff0c;之前配置的姿勢有些問題&#xff0c;告警有些問題&#xff0c;現在調試OK&#xff0c;在此將關鍵配置點簡單記錄下。 關鍵的配置項主要有&#xff1a; 定義告警規則并配置將告警信息通過管道交…

WPF 實現抽屜菜單

分享一個WPF 實現抽屜菜單抽屜菜單作者&#xff1a;WPFDevelopersOrg原文鏈接&#xff1a;https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用大于等于.NET40&#xff1b;Visual Studio 2022;項目使用 MIT 開源許可協議&#xff1b;更多效果可以通過GitHub[1]|碼云[2]…

selenium 定制啟動 chrome 的選項

2019獨角獸企業重金招聘Python工程師標準>>> selenium 定制啟動 chrome 的選項 博客分類&#xff1a; java 搜索引擎&#xff0c;爬蟲 使用 selenium 時&#xff0c;我們可能需要對 chrome 做一些特殊的設置&#xff0c;以完成我們期望的瀏覽器行為&#xff0c;比如…