简体   繁体   English

模块'keras.preprocessing.image'没有属性'ndim'-自定义resnet50转移学习

[英]module 'keras.preprocessing.image' has no attribute 'ndim' - custom resnet50 transfer learning

I was trying to train the keras resnet50 model on a fruits dataset and have been able to do that. 我试图在水果数据集上训练keras resnet50模型,并且已经能够做到这一点。 The model get generated but when I use it to perform prediction on a single image I am getting this error. 该模型已生成,但是当我使用它对单个图像执行预测时,出现此错误。

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

Here is the training code: 这是培训代码:

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")

As said, the model is getting created. 如上所述,正在创建模型。 I ve used the following to test single image prediction 我用以下方法测试了单幅图像预测

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)

In predictFromImagePath function, when returning you are passing image module to the predictFromImage function. predictFromImagePath函数中,返回时将image模块传递给predictFromImage函数。

return predictFromImage(image)

Based on the code above the line I assume you want to call predictFromImage function on variable x . 基于该行上方的代码,我假设您要在变量x上调用predictFromImage函数。 So change the above function call to the following. 因此,将上面的函数调用更改为以下内容。

return predictFromImage(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ResNet50 Model 没有在 keras 中使用迁移学习进行学习 - ResNet50 Model is not learning with transfer learning in keras 如何解决? AttributeError: 模块 'keras.preprocessing.image' 没有属性 'load_img' - HOW TO FIX IT? AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img' AttributeError: 模块 'keras.preprocessing.image' 没有属性 'img_to_array' - AttributeError: module 'keras.preprocessing.image' has no attribute 'img_to_array' 性能不佳的迁移学习 ResNet50 - Poor performance transfer learning ResNet50 ResNet50在喀拉拉邦进行转移学习时,损失总是归功于南 - Loss always go to nan when transfer learning by ResNet50 in keras 使用Keras ResNet50模型制作Python转移学习以停止工作 - Transfer learning with Keras ResNet50 model making python to stop working 如何在具有不同图像尺寸的预训练ResNet50上进行转学习 - How to do transfer learning on a pre-trained ResNet50 with different image size 如何使用自己的数据集对 resnet50 模型进行迁移学习? - How to fo transfer learning of a resnet50 model with with own dataset? resnet50 迁移学习期间的大规模过拟合 - Massive overfit during resnet50 transfer learning 使用fit_generator的Keras传输学习Resnet50获得了较高的acc,但存在val_acc较低的问题 - Keras Transfer Learning Resnet50 using fit_generator got high acc but low val_acc problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM