代码之家  ›  专栏  ›  技术社区  ›  g_p

路缘石致密层形状误差

  •  2
  • g_p  · 技术社区  · 7 年前

    我正在使用keras创建一个LSTM模型。在训练中,我犯了这个错误。

    ValueError: Error when checking target: expected dense_4 to have shape (1,) but got array with shape (34,)

    这是我的模型

    model = Sequential()
    
    model.add(Embedding(max_words, embedding_dim, input_length=maxlen))    
    model.add(LSTM(128, activation='relu'))
    model.add(Dense(64, activation='relu'))
    model.add(Dropout(0.5))
    
    model.add(Dense(units = 34 ,activation='softmax'))
    
    model.layers[0].set_weights([embedding_matrix])
    model.layers[0].trainable = False
    
    model.compile(optimizer='rmsprop',loss='sparse_categorical_crossentropy',metrics=['acc'])
    

    模型摘要:

    Layer (type)                 Output Shape              Param #   
    =================================================================
    embedding_2 (Embedding)      (None, 15, 50)            500000    
    _________________________________________________________________
    lstm_2 (LSTM)                (None, 128)               91648     
    _________________________________________________________________
    dense_3 (Dense)              (None, 64)                8256      
    _________________________________________________________________
    dropout_2 (Dropout)          (None, 64)                0         
    _________________________________________________________________
    dense_4 (Dense)              (None, 34)                2210      
    =================================================================
    Total params: 602,114
    Trainable params: 102,114
    Non-trainable params: 500,000
    _________________________________________________________________
    

    我叫fit

    history = model.fit(X_train, y_train,epochs=100,batch_size=128)
    

    y_train 是一个带有形状的热编码标签 (299, 34) . X_train 有型的 (299, 15) .

    我不确定 为什么模型在寻找形状(1,)正如我所看到的 dense_4 (Dense) 输出形状为`(无,34)。

    1 回复  |  直到 7 年前
        1
  •  1
  •   g_p    7 年前

    好吧,我找到问题了。我将此作为答案发布,以便它也可以帮助其他面临同样问题的人。

    这不是层配置,而是错误的损失函数。

    我在用 sparse_categorical_crossentropy 当标签必须具有形状时作为损失 [batch_size] 以及数据类型int32或int64。我变了是为了 categorical_crossentropy 期望标签为[batch_size,num_classes]。

    keras抛出的错误消息具有误导性。