pred=model.predict\u classes([prepare(file\u path)])AttributeError:“Functional”对象没有属性“predict\u classes”

2024-04-16 23:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将我的keras模型加载到tkinter上改进的蝴蝶物种分类器上,我认为问题在于我如何训练我的模型

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)

上面是我用来训练keras模型的代码,但是当我试图使用蝴蝶分类器预测一个类时,我得到了这个错误

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


Tags: topathfromtestimportjsonimgsize
1条回答
网友
1楼 · 发布于 2024-04-16 23:45:29

我复制了你的代码。因为我没有你的数据集,所以我使用了我自己的数据集,它有两个类。一个错误是行x=densite(15,activation='sigmoid')(x)。由于您正在进行分类,您的激活应该是activation='softmax'。代码的其余部分似乎运行正常

相关问题 更多 >