【问题标题】:module 'keras.preprocessing.image' has no attribute 'ndim' - custom resnet50 transfer learning模块 'keras.preprocessing.image' 没有属性 'ndim' - 自定义 resnet50 迁移学习
【发布时间】:2019-05-10 14:14:33
【问题描述】:

我试图在水果数据集上训练 keras resnet50 模型,并且能够做到这一点。该模型已生成,但当我使用它对单个图像执行预测时出现此错误。

module 'keras.preprocessing.image' has no attribute 'ndim'

这是训练代码:

from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
import OpenSSL
import os

HEIGHT = 100
WIDTH = 100
TRAIN_DIR = "dataset"
BATCH_SIZE = 8


base_model = ResNet50(weights='imagenet', 
                      include_top=False, 
input_shape=(HEIGHT, WIDTH, 3))



train_datagen =  ImageDataGenerator(
      preprocessing_function=preprocess_input,
      rotation_range=90,
      horizontal_flip=True,
      vertical_flip=True
    )

train_generator = train_datagen.flow_from_directory(TRAIN_DIR, 
                                                    target_size=(HEIGHT, WIDTH), 
batch_size=BATCH_SIZE)

from keras.layers import Dense, Activation, Flatten, Dropout
from keras.models import Sequential, Model
def build_finetune_model(base_model, dropout, fc_layers, num_classes):
    for layer in base_model.layers:
        layer.trainable = False

    x = base_model.output
    x = Flatten()(x)
    for fc in fc_layers:
        # New FC layer, random init
        x = Dense(fc, activation='relu')(x) 
        x = Dropout(dropout)(x)

    # New softmax layer
    predictions = Dense(num_classes, activation='softmax')(x) 

    finetune_model = Model(inputs=base_model.input, outputs=predictions)

    return finetune_model


class_list = os.listdir(os.path.join(os.getcwd(),"dataset"))
FC_LAYERS = [1024, 1024]
dropout = 0.5
finetune_model = build_finetune_model(base_model, 
                                  dropout=dropout, 
                                  fc_layers=FC_LAYERS, 
num_classes=len(class_list))

from keras.optimizers import SGD, Adam

NUM_EPOCHS = 6
BATCH_SIZE = 8
num_train_images = 1000

adam = Adam(lr=0.00001)
finetune_model.compile(adam, loss='categorical_crossentropy', metrics=['accuracy'])

filepath="./checkpoints/" + "ResNet50" + "_model_weights.h5"
checkpoint = ModelCheckpoint(filepath, monitor=["acc"], verbose=1, mode='max')
callbacks_list = [checkpoint]

history = finetune_model.fit_generator(train_generator, epochs=NUM_EPOCHS, workers=8, 
                                   steps_per_epoch=num_train_images // BATCH_SIZE, 
                                   shuffle=True, callbacks=callbacks_list)


finetune_model.save("mymodel.hdf5")

如前所述,模型正在创建中。我已经使用以下方法来测试单张图像预测

import numpy as np
import os

from keras.models import load_model
import os
import cv2
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input

model = load_model("mymodel.hdf5")
fruits = os.listdir(os.path.join(os.getcwd(),'dataset'))



def predictFromImagePath(img_path):
    img = image.load_img(img_path, target_size=(100,100))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    print(x.shape)

    return predictFromImage(image)



def predictFromImage(image):

    index = model.predict(image)

    print(index)

    return fruits[index]


if __name__ == "__main__":
    img_path = 'apple1.jpg'   
    predictFromImagePath(img_path)

【问题讨论】:

    标签: python keras resnet transfer-learning


    【解决方案1】:

    predictFromImagePath 函数中,返回时您将image 模块传递给predictFromImage 函数。

    return predictFromImage(image)
    

    根据上面的代码,我假设您想在变量x 上调用predictFromImage 函数。所以把上面的函数调用改成下面这样。

    return predictFromImage(x)
    

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 2019-12-31
      • 2022-11-04
      • 2021-06-03
      • 2021-09-05
      • 2022-10-24
      • 2018-10-26
      • 2022-11-10
      • 2022-07-18
      相关资源
      最近更新 更多