【问题标题】:Keras layer shape incompatibility for a small MLP小型 MLP 的 Keras 层形状不兼容
【发布时间】:2020-06-24 09:58:47
【问题描述】:

我在 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 从来没有这样做过。

【问题讨论】:

    标签: tensorflow machine-learning keras mlp


    【解决方案1】:

    在输入层使用 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)
    

    【讨论】:

    • 嗨。我的问题是 n_sample = n_classes。
    • 在你的最后一个密集层中传递 n_sample(这是一个非常奇怪的问题,我不希望有好的结果)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多