【问题标题】:Keras: Input layer and passing input data correctlyKeras:输入层并正确传递输入数据
【发布时间】:2018-12-22 21:01:39
【问题描述】:

我正在学习使用 Keras 函数式 API,并且我已经成功地构建和编译了一个模型。但是当我调用model.fit 传递数据X 和标签y 时,出现错误。看来我还是不知道它是如何工作的。

任务是把句子分成6种,代码如下:

X_ = ... # shape: (2787, 100) each row a sentence and each column a feature
y_= ... # shape: (2787,)

word_matrix_weights= ... # code to initiate a lookup matrix for vocabulary embeddings. shape: (9825,300)

deep_inputs = Input(shape=(100,))
embedding = Embedding(9825, 300, input_length=100,
                      weights=[word_matrix_weights], trainable=False)(deep_inputs)
flat = Flatten()(embedding)
hidden = Dense(6, activation="softmax")(flat)

model = Model(inputs=deep_inputs, outputs=hidden)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(x=X_,y=y_,epochs=100, batch_size=10, verbose=0) #error here

最后一行产生错误:

  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1555, in fit
    batch_size=batch_size)
  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1413, in _standardize_user_data
    exception_prefix='target')
  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 154, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target: expected dense_1 to have shape (None, 6) but got array with shape (2878, 1)

有什么建议吗?

【问题讨论】:

    标签: python machine-learning keras nlp classification


    【解决方案1】:

    您有一个具有 6 个单元的 Dense 层,最后一层是 softmax 激活。所以它的输出将是(?,6) 的形状,其中这 6 个值中的每一个都表示属于相应类别的概率。由于您使用categorical_crossentropy 作为损失函数,因此标签(即y_)也应该具有相同的形状(即(2787,6))。您可以使用to_categorical 方法对y_ 进行一次热编码:

    from keras.utils import to_categorical
    
    y_ = to_categorical(y_)
    

    这个 one-hot 对标签进行编码,即将 3 转换为 [0,0,0,1,0,0](假设标签编号从零开始)。

    如果您不想一次性对标签进行编码,可以将 loss 参数更改为 'sparse_categorical_crossentropy'

    【讨论】:

    • 谢谢,我认为它有效。当我使用顺序模型时,我不必这样做。是因为它会自动为我解决这个问题吗?
    • @Ziqi 你确定吗?如果是这样就很奇怪......不,你使用顺序模型还是函数式api都没有关系;根据最后一层和使用的损失函数,标签应该具有预期的形状。
    猜你喜欢
    • 2019-01-14
    • 2017-09-19
    • 1970-01-01
    • 2018-03-08
    • 2019-01-29
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多