我正在学习转学,但出现了“ np.expand_dims”错误

时间:2019-04-23 15:21:58

标签: python keras deep-learning prediction

我正在使用VGG16模型,我冻结了所有卷积层,删除了最后一个密集层(预测一个),并为我自己的层进行了更改(3个输出)。

如果有帮助:火车= 200张图像,有效= 8,测试= 10

这是我的代码。

train_path = 'animals/train'
valid_path = 'animals/valid'
test_path = 'animals/test'

train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224, 224), classes=['DOLPHIN', 'SHARK', 'WHALE'], batch_size=10)
valid_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224, 224), classes=['DOLPHIN', 'SHARK', 'WHALE'], batch_size=4)
test_batch = ImageDataGenerator().flow_from_directory(test_path, target_size=(224, 224), classes=['DOLPHIN', 'SHARK', 'WHALE'], batch_size=10)

vgg16 = keras.applications.vgg16.VGG16()

my_model = Sequential()
for layer in vgg16.layers[:-1]:
    my_model.add(layer)

for layer in my_model.layers:
    layer.trainable = False

my_model.add(Dense(3, activation='softmax'))

my_model.compile(
    loss="categorical_crossentropy",
    optimizer=Adam(lr=0.00001), 
    metrics=['accuracy']
)

start = time.time()
# Train the model
my_model.fit(
    train_batches,
    steps_per_epoch=20,
    epochs=5,
    validation_data=valid_batches,
    validation_steps=4
)

这是错误

Traceback (most recent call last):
  File "C:/Users/Arlex/PycharmProjects/CNN/VGG_ANIMALS/01_loading_images_training.py", line 61, in <module>
    validation_steps=4
  File "C:\Users\Arlex\PycharmProjects\CNN\venv\lib\site-packages\keras\models.py", line 1002, in fit
    validation_steps=validation_steps)
  File "C:\Users\Arlex\PycharmProjects\CNN\venv\lib\site-packages\keras\engine\training.py", line 1630, in fit
    batch_size=batch_size)
  File "C:\Users\Arlex\PycharmProjects\CNN\venv\lib\site-packages\keras\engine\training.py", line 1476, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\Arlex\PycharmProjects\CNN\venv\lib\site-packages\keras\engine\training.py", line 76, in _standardize_input_data
    data = [np.expand_dims(x, 1) if x is not None and x.ndim == 1 else x for x in data]
  File "C:\Users\Arlex\PycharmProjects\CNN\venv\lib\site-packages\keras\engine\training.py", line 76, in <listcomp>
    data = [np.expand_dims(x, 1) if x is not None and x.ndim == 1 else x for x in data]
AttributeError: 'DirectoryIterator' object has no attribute 'ndim'

1 个答案:

答案 0 :(得分:0)

您不能将model.fit与生成器一起使用,因为您必须使用model.fit_generator