keras中使用預訓練模型進行圖片分類


keras中含有多個網絡的預訓練模型,可以很方便的拿來進行使用。

安裝及使用主要參考官方教程:https://keras.io/zh/applications/   https://keras-cn.readthedocs.io/en/latest/other/application/

官網上給出了使用 ResNet50 進行 ImageNet 分類的樣例

from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

model = 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)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
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)]

那么對於其他的網絡,便可以參考此代碼

首先vgg19

# coding: utf-8
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.applications.vgg19 import preprocess_input
from keras.models import Model
import numpy as np
base_model = VGG19(weights='imagenet', include_top=True)
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output)
img_path = '../mdataset/img_test/p2.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)
fc2 = model.predict(x)
print(fc2.shape)  #(1, 4096)
View Code

然后mobilenet

# coding: utf-8
from keras.applications.mobilenet import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input,decode_predictions
from keras.models import Model
import numpy as np
import time

model = MobileNet(weights='imagenet', include_top=True,classes=1000)

start = time.time()

img_path = '../mdataset/img_test/dog.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)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=15)[0])
end = time.time()

print('time:\n')
print str(end-start)
View Code

時間統計時偽統計加載模型的時間,大概需要不到1秒,如果把加載模型的時間算進去,大概3s左右


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM