从预训练模型中加载图像分类模型的代码示例。
发布时间:2024-01-01 13:26:57
在加载预训练模型作为图像分类模型之前,我们需要先安装必要的软件包。常用的深度学习库包括TensorFlow和PyTorch,我们可以根据需求选择其中一个库。以下是TensorFlow和PyTorch两个库的示例代码。
使用TensorFlow加载预训练模型的示例代码如下:
import tensorflow as tf
from tensorflow.keras.applications import ResNet50
# 加载ResNet50模型
model = ResNet50(weights='imagenet')
# 加载图像分类模型
def classify_image(image_path):
# 读取图像
image = tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
# 图像预处理
image = tf.keras.preprocessing.image.img_to_array(image)
image = tf.keras.applications.resnet50.preprocess_input(image)
# 图像分类
predictions = model.predict(tf.expand_dims(image, axis=0))
# 返回分类结果
return tf.keras.applications.resnet50.decode_predictions(predictions, top=3)[0]
# 使用图像分类模型
image_path = 'image.jpg'
predictions = classify_image(image_path)
for prediction in predictions:
print(f'{prediction[1]}: {prediction[2]*100:.2f}%')
使用PyTorch加载预训练模型的示例代码如下:
import torch
import torchvision.models as models
from torchvision import transforms
# 加载ResNet模型
model = models.resnet50(pretrained=True)
# 加载图像分类模型
def classify_image(image_path):
# 读取图像
image = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])(Image.open(image_path))
# 图像分类
with torch.no_grad():
predictions = model(torch.unsqueeze(image, 0))
# 返回分类结果
return predictions
# 使用图像分类模型
image_path = 'image.jpg'
predictions = classify_image(image_path)
top_predictions = torch.topk(predictions, k=3)
for i, idx in enumerate(top_predictions.indices.squeeze()):
print(f'{i+1}. {imagenet_labels[idx]}: {top_predictions.values.squeeze()[i]*100:.2f}%')
以上代码示例中,我们首先加载了预训练的图像分类模型(这里分别使用了ResNet50),然后定义classify_image()函数来对输入的图像进行分类。在使用函数时,我们需要提供待分类的图像路径。输出结果为图像的分类概率和标签,并按照概率从高到低进行排序。
需要注意的是,TensorFlow和PyTorch的处理输入图像的方式略有不同。在TensorFlow中,我们使用tf.keras.preprocessing来预处理图像;而在PyTorch中,我们使用torchvision.transforms进行图像预处理。
