为什么在尝试拟合卷积模型时会发生此错误?

时间:2020-10-25 19:41:45

标签: keras neural-network runtime-error conv-neural-network

我正在尝试对猫和狗进行图像分类,这是我当前的代码:

from keras import Sequential
from keras_preprocessing.image import ImageDataGenerator
from keras.layers import *
import numpy as np
import cv2
import os

#Squish Images
img_size = 500 # number of pixels for width and height
#def squish_image(filepath):
#    img = cv2.imread(filepath, cv2.IMREAD_COLOR)
#    img_resized = cv2.resize(img, (img_size,img_size))
#    return img_resized.reshape(-1, img_size, img_size, 1)


#Random Seed
np.random.seed(12321)


training_path = os.getcwd() + "/cats and dogs images/train"
testing_path = os.getcwd() + "/cats and dogs images/test"

#Defines the Model
model = Sequential([
    Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same", input_shape= 
(img_size,img_size,3)),
    MaxPool2D(pool_size=(2,2), strides=2),
    Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same"),
    MaxPool2D(pool_size=(2,2), strides=2),
    Flatten(),
    Dense(32, activation="relu"),
    Dense(1, activation="sigmoid")
])


#Scales the pixel values to between 0 to 1
datagen = ImageDataGenerator(rescale=1.0/255.0)

#Prepares Training Data
training_dataset = ImageDataGenerator(datagen.flow_from_directory(directory = training_path, 
target_size=(img_size,img_size), classes = ["cat","dog"], batch_size = 133))

#Prepares Testing Data
testing_dataset = ImageDataGenerator(datagen.flow_from_directory(directory = testing_path, 
target_size=(img_size,img_size), classes = ["cat","dog"], batch_size = 133))


#Compiles the model
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy'])

#Fitting the model to the dataset (Training the Model)
fitted_model = model.fit(training_dataset, steps_per_epoch = 94, validation_data=testing_dataset, 
validation_steps=94, epochs = 20, verbose = 1)


# evaluate model on training dataset
_, acc = model.evaluate_generator(training_dataset, steps=len(training_dataset), verbose=0)
print("Accuracy on training dataset:")
print('> %.3f' % (acc * 100.0))


#evaluate model on testing dataset
_, acc = model.evaluate_generator(testing_dataset, steps=len(testing_dataset), verbose=0)
print("Accuracy on testing dataset:")
print('> %.3f' % (acc * 100.0))

##Saving the Model:
# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")

但是,当我运行它时,出现此错误:

Found 12502 images belonging to 2 classes.
Found 12491 images belonging to 2 classes.
Traceback (most recent call last):
  File "C:\Users\Jackson\Documents\Programming\Python Projects\Neural Network That Deteremines Cats and Dogs\Training Network.py", line 52, in <module>
    fitted_model = model.fit(training_dataset, steps_per_epoch = 94, validation_data=testing_dataset, validation_steps=94, epochs = 20, verbose = 1)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1049, in fit
    data_handler = data_adapter.DataHandler(
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py", line 1104, in __init__
    adapter_cls = select_data_adapter(x, y)
  File "C:\Users\Jackson\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py", line 968, in select_data_adapter
    raise ValueError(
ValueError: Failed to find data adapter that can handle input: <class 'keras_preprocessing.image.image_data_generator.ImageDataGenerator'>, <class 'NoneType'>

请忽略已注释掉的代码,因为我仍在进行实验,因此不能以最有效的方式实现所有内容。

我不了解<class 'NoneType >是什么,因为我认为我添加了运行模型所需的参数,所以我在做什么错了?

0 个答案:

没有答案