How to utilize pre-trained models in Keras?
There are two ways to use pre-trained models in Keras: either by utilizing pre-trained models already provided in Keras (such as VGG16, ResNet50, InceptionV3, etc.) or by using models trained in other deep learning frameworks (like TensorFlow, PyTorch).
- Utilize the pre-trained models provided by Keras.
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input, decode_predictions
from keras.preprocessing import image
import numpy as np
# 加载预训练的VGG16模型
model = VGG16(weights='imagenet')
# 加载要预测的图片,并进行预处理
img_path = 'path_to_your_image.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)
predictions = decode_predictions(preds, top=3)[0]
for i, (imagenetID, label, score) in enumerate(predictions):
print("{}. {}: {:.2f}%".format(i + 1, label, score * 100))
- Utilize models trained in other deep learning frameworks.
import tensorflow as tf
from keras.applications.vgg16 import preprocess_input
from keras.preprocessing import image
import numpy as np
# 加载其他深度学习框架中训练好的模型
model = tf.keras.models.load_model('path_to_your_model.h5')
# 加载要预测的图片,并进行预处理
img_path = 'path_to_your_image.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)
You can use pre-trained models in Keras for tasks such as image classification and object detection using the two methods mentioned above.