我如何在模型中使用38个类而不是1000个.predict解码预测

时间:2019-03-26 16:47:09

标签: tensorflow keras deep-learning transfer-learning

每当它在decode_predictions中引发错误消息时,我就使用resnet50深度学习模型发现植物病害检测错误

错误

期望一批预测(即形状的2D数组(样本,1000个))。找到形状为((1,38)“的数组

enter code here


model = ResNet50(weights='imagenet',include_top=False,classes=38)

try:
model = load_model('/content/drive/My 
Drive/color/checkpoints/ResNet50_model_weights.h5')
print("model loaded")  
except:
print("model not loaded")

img_path = '/content/drive/My Drive/color/test/0/appleblackrot188.jpg' 
img = image.load_img(img_path, target_size=(300, 300))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
print('Predicted:', decode_predictions(preds,top=3)[0])

3 个答案:

答案 0 :(得分:0)

您可以尝试使用预处理功能:

import tensorflow as tf
# Using the keras wrapper on tensorflow (it must be the same using just keras).

IMAGE = [] # From image source, i did it from the camera.

toPred = tf.keras.applications.resnet50.preprocess_input(np.expand_dims(tf.keras.preprocessing.image.img_to_array(IMAGE), axis=0))

也许可以帮助您:)

答案 1 :(得分:0)

decode_predictions仅适用于ImageNet(类数= 1000)。对于这38种植物,您必须根据为每种植物分配的地面真相标签编写自己的解码预测。

答案 2 :(得分:0)

首先,您需要一个索引JSON文件并创建一个新的encode_predictions函数。 例如

此HAM10000具有7个类,您需要像这样拆分到每个文件夹

enter image description here

然后创建一个这样的索引JSON文件

{
"0" : [
    "AKIEC",
    "akiec"
],
"1" : [
    "BCC",
    "bcc"
],
"2" : [
    "BKL",
    "bkl"
],
"3" : [
    "DF",
    "df"
],
"4" : [
    "MEL",
    "mel"
],
"5" : [
    "NV",
    "nv"
],
"6" : [
    "VASC",
    "vasc"
]

}

然后尝试此代码

def decode_predictions(preds, top=4, class_list_path='/content/SKIN_DATA/HAM10000_index.json'):
  if len(preds.shape) != 2 or preds.shape[1] != 7: # your classes number
    raise ValueError('`decode_predictions` expects '
                     'a batch of predictions '
                     '(i.e. a 2D array of shape (samples, 1000)). '
                     'Found array with shape: ' + str(preds.shape))
  index_list = json.load(open(class_list_path))
  results = []
  for pred in preds:
    top_indices = pred.argsort()[-top:][::-1]
    result = [tuple(index_list[str(i)]) + (pred[i],) for i in top_indices]
    result.sort(key=lambda x: x[2], reverse=True)
    results.append(result)
  return results