【问题标题】:Keras conv2d input shape errorKeras conv2d 输入形状错误
【发布时间】:2018-08-15 03:13:31
【问题描述】:

无法解决 keras 输入形状错误的问题。如何在 conv2d 层中实际指定尺寸是未知的。尝试了不同的方法,仍然无法正常工作。下面提到的是我尝试使用 keras 为 mnist 数据集实现卷积网络的代码。该阵列最初是 1x784。但是我把它改成 28x28 还是不行。谁能告诉我我做错了什么。谢谢!

batch_size = 32
epochs = 20
number_of_classes = 10

def build_brain():
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(28,28,1)))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))
    model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
    return model

def shared_dataset(data_xy):
    data_x, data_y = data_xy
    shared_x = np.asarray(data_x)
    shared_y = np.asarray(data_y)
    return shared_x, shared_y

f = gzip.open('mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = pickle.load(f,encoding='latin1')
f.close()

test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set)


train_set_x = train_set_x.reshape(-1,28,28)
valid_set_x = valid_set_x.reshape(-1,28,28)
test_set_x = test_set_x.reshape(-1,28,28)


brain = build_brain()
asd = brain.fit(train_set_x, train_set_y, epochs=30, validation_data = (valid_set_x, valid_set_y), batch_size=32)
score = brain.evaluate(test_set_x, test_set_y, batch_size = 32)
print('Test score:', score[0])
print('Test accuracy:', score[1])

【问题讨论】:

    标签: python-3.x keras convolution mnist


    【解决方案1】:

    这是你的问题:

    train_set_x = train_set_x.reshape(-1,28,28)
    valid_set_x = valid_set_x.reshape(-1,28,28)
    test_set_x = test_set_x.reshape(-1,28,28)
    

    正如您使用 input_shape = (28, 28, 1) 一样,网络需要具有形状 (samples, 28, 28, 1) 的训练输入。所以正确的重塑是:

    train_set_x = train_set_x.reshape(-1, 28, 28, 1)
    valid_set_x = valid_set_x.reshape(-1, 28, 28, 1)
    test_set_x = test_set_x.reshape(-1, 28, 28, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多