小型MLP的Keras层形状不兼容

时间:2020-06-24 09:58:47

标签: tensorflow machine-learning keras mlp

我有一个在Keras中构建的简单MLP。我输入的形状是:

X_train.shape - (6, 5)
Y_train.shape - 6
  

创建模型

model = Sequential()
model.add(Dense(32, input_shape=(X_train.shape[0],), activation='relu'))
model.add(Dense(Y_train.shape[0], activation='softmax'))
# Compile and fit
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, Y_train, epochs=10, batch_size=1, verbose=1, validation_split=0.2)
# Get output vector from softmax
output = model.layers[-1].output

这给了我错误:

ValueError: Error when checking input: expected dense_1_input to have shape (6,) but got array with shape (5,). 

我有两个问题:

  1. 为什么会出现上述错误,我该如何解决?
  2. output = model.layers[-1].output是针对给定输入向量返回softmax向量的方法吗?我从未在Keras中做到过。

1 个答案:

答案 0 :(得分:2)

在输入层中使用input_shape =(X_train.shape [1],),而最后一层的尺寸必须等于要预测的类数

返回softmax向量的方法是model.predict(X)

这里是一个完整的示例

n_sample = 5
n_class = 2
X = np.random.uniform(0,1, (n_sample,6))
y = np.random.randint(0,n_class, n_sample)

model = Sequential()
model.add(Dense(32, input_shape=(X.shape[1],), activation='relu'))
model.add(Dense(n_class, activation='softmax'))

# Compile and fit
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, epochs=10, batch_size=1, verbose=1)

# Get output vector from softmax
model.predict(X)