tensorflow - 使用 TensorFlow Hub 进行迁移学习:使用单个测试图像?
问题描述
我已经成功地遵循了关于使用迁移学习进行图像分类的官方教程:https ://www.tensorflow.org/tutorials/images/transfer_learning_with_hub
我的实验模型现在已保存,并且应该在看到“好”画作时进行识别。但是,我想用模型以前从未见过的图像对此进行测试。到目前为止,我只使用了数据集已经分为训练和测试文件夹的笔记本。但是,这里不是这种情况。
我想我需要类似的东西
img = tf.keras.preprocessing.image.load_img("/content/mytestimage.jpeg", target_size=(224,224))
除其他事项外; 但是,对于初学者来说,看看这种测试预测的例子会很有用。到目前为止,我已经搜索了没有结果 - 如果有人有任何建议,我很高兴听到!
解决方案
以下是使用 keras 进行 mobilenet 迁移学习的方法,但大部分代码应该相同。可以在此处找到完整的迁移学习教程。我发现它非常有用。
from PIL import Image
from tensorflow.keras.models import load_model
model = load_model('path/to/model.h5')
img = Image.open(file)
array = np.asarray(img, dtype=np.float32)
arrayexp = np.expand_dims(array, axis=0)
arrayexp = (arrayexp/127)-1 #This is a normalization factor specifically for Mobilenet but I think it's used for many other networks
result = model.predict(arrayexp)
print(np.argmax(result)) #Prints class with highest confidence
print(result[0][np.argmax(result)]) #Prints confidence for the highest