错误-AttributeError:'DirectoryIterator'对象在keras中的自动编码器设计中没有属性'ndim

时间:2018-10-12 12:30:21

标签: python keras autoencoder

我是Python 3.5的新手。我正在尝试编写一个简单的自动编码器,该编码器将在包含60张苹果图像的数据集上进行训练,并尝试重建根中给出的图像。我使用了以下代码:

from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
from PIL import Image 
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
image = Image.open('C:\Python35\Scripts\apple.jpg')
encoding_dim = 32
input_img = Input(shape=(65536,))
encoded = Dense(encoding_dim, activation='relu')(input_img)
decoded = Dense(65536, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
encoder = Model(input_img, encoded)
encoded_input = Input(shape=(encoding_dim,))
decoder_layer = autoencoder.layers[-1]
decoder = Model(encoded_input, decoder_layer(encoded_input))
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
train_datagen=ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    directory=r"C:\Users\vlsi\Desktop\train",
    batch_size=32,
    class_mode="categorical",
    shuffle=True,
    seed=42
)
autoencoder.fit(train_generator,
                epochs=2,
                batch_size=256,
                shuffle=True)
encoded_img = encoder.predict(np.array(image))
decoded_img = decoder.predict(encoded_img)
plt.imshow(decoded_img)

出现错误

  

AttributeError:“ DirectoryIterator”对象没有属性“ ndim”

知道发生了什么事吗?

1 个答案:

答案 0 :(得分:5)

Keras fit函数接收数据数组,numpy数组而不是生成器。您需要的功能是fit_generator。请注意,fit_generator的参数稍有不同,例如steps_per_epoch而不是batch_size