简体   繁体   中英

pred = model.predict_classes([prepare(file_path)]) AttributeError: 'Functional' object has no attribute 'predict_classes'

I am trying to load in my keras model on a modified butterfly species classifier on tkinter I think the problem lies within how I trained my model

import cv2
import tensorflow as tf

CATEGORIES = ["Abyssinians", "American Shorthair", "Bengals", "Birman",
              "British Shorthairs", "Devon Rex", "Exotic Shorthairs", "Maine Coon",
              "Oriental Shorthairs", "Persians", "Ragdoll", "Scottish Folds", "Siamese", "Somali", "Sphynx"]  # will use this to convert prediction num to string value
def prepare(filepath):
    IMG_SIZE = 100 # 50 in txt-based
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)  # read in the image, convert to grayscale
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))  # resize image to match model's expected sizing
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)  # return the image with shaping that TF wants.

model = tf.keras.models.load_model("CAT_BREEDS.model")

prediction = model.predict([prepare(r'D:\Desktop\CATS\validation\Abyssinians\45997693_52.jpg')])
print(prediction)

above are the codes I used to train my keras model but when trying to predict a class using the butterfly classifier I get this error

pred = model.predict_classes([prepare(file_path)]) AttributeError: 'Functional' object has no attribute 'predict_classes'

import numpy as np from tensorflow import keras from tensorflow.keras.layers import Dense, GlobalAveragePooling2D from tensorflow.keras.optimizers import Adam from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.models import Model from sklearn.metrics import confusion_matrix import itertools import matplotlib.pyplot as plt

train_path=r'D:\Desktop\CATS - Copy 2\train' valid_path=r'D:\Desktop\CATS - Copy 2\validation' test_path=r'D:\Desktop\CATS - Copy 2\test'

class_labels=["Abyssinians", "American Shorthair", "Bengals", "Birman", "British Shorthairs", "Devon Rex", "Exotic Shorthairs", "Maine Coon", "Oriental Shorthairs", "Persians", "Ragdoll", "Scottish Folds", "Siamese", "Somali", "Sphynx"]

train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)
.flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5) valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)
.flow_from_directory(valid_path, target_size=(299,299),classes=class_labels,batch_size=5) test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)
.flow_from_directory(test_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)

base_model=keras.applications.xception.Xception(include_top=False)

x=base_model.output x=GlobalAveragePooling2D()(x) x=Dense(1024, activation='relu')(x) x=Dense(15, activation='sigmoid')(x) model=Model(inputs=base_model.input, outputs=x)

base_model.trainable = False

N=1

model.compile(Adam(lr=.0001),loss='categorical_crossentropy', metrics=['accuracy']) history=model.fit_generator(train_batches, steps_per_epoch=200, validation_data=valid_batches, validation_steps=90,epochs=N,verbose=1)

model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights('model_weights.h5')

print("[INFO]evaluating model...")

test_labels=test_batches.classes predictions=model.predict_generator(test_batches, steps=28, verbose=1)

model.save('CAT_BREEDS.model')

I copied your code. Since I do not have your dataset I used my own which had 2 classes.One error is the line x=Dense(15, activation='sigmoid')(x). Since you are doing classification your activation should be activation='softmax'. The rest of the code seemed to run OK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM