在搭建了深度学习环境后,第一件事就是试试行不行,最简单的当然是使用已经训练好的模型拿来预测新样本了。这里我们使用kaggle上面训练好的狗狗品种预测模型进行使用说明。(后面有完整的数据和脚本,下载到本地即可运行。)
1.加载待预测图片
from os.path import join
image_dir = 'train/'
img_paths = [join(image_dir, filename) for filename in
['0246f44bb123ce3f91c939861eb97fb7.jpg',
'84728e78632c0910a69d33f82e62638c.jpg']]
这里选用了2张图片,保存在img_paths的list里面。
2.定义读取和预处理图片的函数
import numpy as np
from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import load_img, img_to_array
image_size = 224
def read_and_prep_images(img_paths, img_height=image_size, img_width=image_size):##定义处理函数
imgs = [load_img(img_path, target_size=(img_height, img_width)) for img_path in img_paths]
img_array = np.array([img_t