Keras正确的多层感知器输入形状

时间:2017-02-14 19:24:36

标签: python neural-network keras perceptron data-formats

我正在尝试在keras中制作一个基本的MLP示例。我的输入数据的形状为train_data.shape = (2000,75,75),我的测试数据的形状为test_data.shape = (500,75,75)2000500是培训和测试数据的样本数量(换句话说,数据的形状为(75,75),但有2000和500条培训和测试数据)。输出应该有两个类。

我不确定在网络的第一层上使用input_shape参数的值是多少。使用keras存储库中mnist示例的代码,我有(更新):

from six.moves    import cPickle
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.utils  import np_utils
from keras.optimizers import RMSprop

# Globals
NUM_CLASSES = 2
NUM_EPOCHS  = 10
BATCH_SIZE  = 250

def loadData():
    fData = open('data.pkl','rb')
    fLabels = open('labels.pkl','rb')
    data = cPickle.load(fData)
    labels = cPickle.load(fLabels)

    train_data = data[0:2000]
    train_labels = labels[0:2000]
    test_data = data[2000:]
    test_labels = labels[2000:]
    return (train_data, train_labels, test_data, test_labels)

# Load data and corresponding labels for model
train_data, train_labels, test_data, test_labels = loadData()

train_labels = np_utils.to_categorical(train_labels, NUM_CLASSES)
test_labels  = np_utils.to_categorical(test_labels, NUM_CLASSES)

print(train_data.shape)
print(test_data.shape)

model = Sequential()
model.add(Dense(512, input_shape=(5625,)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(2))
model.add(Activation('softmax'))

model.summary()

model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

history = model.fit(train_data, train_labels, validation_data=(test_data, test_labels), 
                    batch_size=BATCH_SIZE, nb_epoch=NUM_EPOCHS,
                    verbose=1)
score = model.evaluate(test_data, test_labels, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])

其中5625为75 * 75(模拟MNIST示例)。我得到的错误是:

Error when checking model input: expected dense_input_1 to have 2 dimensions, but got array with shape (2000, 75, 75)

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

来自keras MLP示例,https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py

# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)

模型输入

model = Sequential()
model.add(Dense(512, input_shape=(784,)))

所以你应该重塑你的火车并测试到(2000,75 * 75)和(500,75 * 75)

train_data = train_data.reshape(2000, 75*75)
test_data = test_data.reshape(500, 75*75)

然后像你一样设置模型输入形状

model.add(Dense(512, input_shape=(75*75,)))