Keras猫狗大战二:加载模型预测单张图片

版权声明:本文为博主原创文章,欢迎转载,并请注明出处。联系方式:460356155@qq.com

 加载https://www.cnblogs.com/zhengbiqing/p/11068529.html训练得到的74%精度的模型,预测图片。

import os
import random
import numpy as np

from keras.preprocessing import image
from keras.models import load_model

model = load_model(r"D:\projects\cats_and_dogs_small_1.h5")
all_num = 12500
num = 100

# 从0~12499随机生成随机数列表
result = random.sample(range(0, all_num), num)

predict_class = 'dog'
class_indices = {'cat': 0, 'dog': 1}

hit_num = 0
hit_val = class_indices.get(predict_class)

for i in range(num):
    file_path = r'D:\BaiduNetdiskDownload\train\%s.%s.jpg' % (predict_class, result[i])

    img = image.load_img(file_path, target_size=(150, 150))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    y = model.predict_classes(x)

    if int(y[0][0]) == hit_val:
        hit_num += 1

print('Predict %s images %s, Acc: %.3f%%' % (predict_class, num, hit_num/num))
Predict dog images 100, Acc: 0.830%
Predict cat images 1000, Acc: 0.661%

预测全部12500张图:
Predict dog images 12500, Acc: 0.832%
Predict cat images 12500, Acc: 0.690%
看来cat比dog更难预测。
posted @ 2019-06-22 16:38  碧水青山  阅读(2632)  评论(0编辑  收藏  举报