温馨提示×

如何在Keras中使用预训练的模型

小樊
85
2024-03-11 11:51:25
栏目: 深度学习

在Keras中使用预训练的模型可以通过两种方式实现:使用已经在Keras中提供的预训练模型(如VGG16、ResNet50、InceptionV3等)或者使用其他深度学习框架(如TensorFlow、PyTorch)中训练好的模型。

  1. 使用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))
  1. 使用其他深度学习框架中训练好的模型:
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)

通过以上两种方法,您可以在Keras中使用预训练的模型进行图像分类、目标检测等任务。

0