Keras形状不起作用

时间:2018-02-01 20:32:11

标签: python keras

我一直在尝试制作自动编码器,而且我遇到了一些问题。所以我正在将32x32灰度图像加载到网络中,它不断给我这个错误。

Using TensorFlow backend.
(32, 32, 1)
253.0
Traceback (most recent call last):
  File "test.py", line 32, in <module>
    model.fit(out,out, batch_size=16, epochs=10)
  File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\models.py", line 965, in fit
    validation_steps=validation_steps)
  File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 1593, in fit
    batch_size=batch_size)
  File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 1426, in _standardize_user_data
    exception_prefix='input')
  File "C:\Users\nathanmoosh\Anaconda3_2\lib\site-packages\keras\engine\training.py", line 110, in _standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected dense_1_input to have 4 dimensions, but got array with shape (32, 32, 1)

这是我的代码。

from keras.models import Sequential
from keras.layers import Dense, Activation,Dropout,Flatten
from keras.preprocessing import image
import numpy
img = image.load_img("imgs/test3.jpg", target_size=(32, 32), grayscale = True)

x = image.img_to_array(img)
out = numpy.array(x)

print(out.shape)
print(out[0][0][0])

model = Sequential()
model.add(Dense(1025, activation='relu', input_shape=(32,32,3)))
model.add(Activation('relu'))
model.add(Dense(512, activation='relu'))
model.add(Activation('relu'))
model.add(Dense(128, activation='relu'))
model.add(Activation('relu'))
model.add(Dense(64, activation='relu'))
model.add(Activation('relu'))
model.add(Dense(128, activation='relu'))
model.add(Activation('relu'))
model.add(Dense(512, activation='relu'))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1024, activation='relu'))
model.add(Activation('relu'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.fit(out,out, batch_size=16, epochs=10)

请帮忙!

1 个答案:

答案 0 :(得分:0)

正如@MatiasValdenegro建议的那样,输入的形状应为(num_samples,32,32,3)。在你的情况下,它是(1,32,32,3),而不是(32,32,3)。

要执行此操作,请在out = numpy.array(x)之后添加以下行:

out = out[numpy.newaxis, :, :, :] # (1, 32, 32, 3)