2017-06-04 199 views
1

我使用的是具有tensorflow後端的Keras 2.04。我試圖在MNIST圖像上用ImageDataGenerator來訓練一個簡單的模型。不過,我一直從fit_generator收到以下錯誤:使用ImageDataGenerator(Keras)時,fit_generator輸入尺寸錯誤

ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with shape (8, 28, 28, 1).

這是代碼:

#loading data & reshaping 
(x_train, y_train), (x_test, y_test) = mnist.load_data() 
x_train = x_train.reshape(x_train.shape[0], 28, 28,1) 

#building the model 
input_img = Input(shape=(784,)) 
encoded = Dense(30, activation='relu')(input_img) 
decoded = Dense(784, activation='sigmoid')(encoded) 
autoencoder = Model(input_img, decoded) 
autoencoder.compile(optimizer='adam', loss='mse') 

#creating ImageDataGenerator 
datagen = ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True) 
datagen.fit(x_train) 

autoencoder.fit_generator(
     #x_train, x_train because the target is to reconstruct the input 
     datagen.flow(x_train, x_train, batch_size=8), 
     steps_per_epoch=int(len(x_train)/8), 
     epochs=64, 
     ) 

據我瞭解ImageDataGenerator應該產生一批訓練實例每次迭代,因爲它實際上做(在這種情況下,batch_size = 8),但從錯誤,它似乎它期望一個單一的訓練示例。

謝謝!

回答

0

解決 - 它應該是:

autoencoder = Sequential() 
autoencoder.add(Reshape((784,), input_shape=(28,28,1))) 
autoencoder.add(Dense(30, activation='relu')) 
autoencoder.add(Dense(784, activation='relu')) 
. 
. 
. 

autoencoder.fit_generator(
     datagen.flow(x_train, x_train.reshape(len(x_train),784,), batch_size=8), 
     steps_per_epoch=int(len(x_train)/8), 
     epochs=64, 
     )