keras的基本用法(五)——图像predict

来源:互联网 发布:算法工程师有哪些证书 编辑:程序博客网 时间:2024/06/05 09:29

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要介绍Keras的一些基本用法,主要是根据已有模型预测图像的类别,以ResNet50为例。

  • Demo
import numpy as npfrom keras.layers import Densefrom keras.models import Modelfrom keras.preprocessing import imagefrom keras.applications.resnet50 import ResNet50# 使用ResNet的结构,不包括最后一层base_model = ResNet50(include_top = False, pooling = 'avg')# 定义网络结构最后一层predictions = Dense(3, activation='softmax')(base_model.output)# 定义模型model = Model(inputs=base_model.input, outputs=predictions)# 加载训练好的模型model.load_weights('./weights.h5')image_path = './lena.jpg'# 加载图像img = image.load_img(image_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:', preds