检查目标时出错:预期density_1的形状为(1,),但数组的形状为(256,)

时间:2018-08-02 19:55:46

标签: numpy machine-learning neural-network keras

我正在尝试学习张量流,并且正在关注一个演示教程(https://www.tensorflow.org/tutorials/keras/basic_text_classification

错误报告告诉我

“检查目标时出错:预期density_1的形状为(1,),但数组的形状为(256,)”

有人可以向我解释为什么这行不通吗?

train_data = keras.preprocessing.sequence.pad_sequences(train_data,
                                                    value=word_index["<PAD>"],
                                                    padding='post',
                                                    maxlen=256) #max length
test_data = keras.preprocessing.sequence.pad_sequences(test_data,
                                                   value=word_index["<PAD>"],
                                                   padding='post',
                                                   maxlen=256)
vocal_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocal_size,16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16,activation=tf.nn.relu))
model.add(keras.layers.Dense(1,activation=tf.nn.sigmoid))

model.compile(optimizer=tf.train.AdamOptimizer(),
          loss='binary_crossentropy',
          metrics=['accuracy'])


x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_data[:10000]
partial_y_train = train_data[10000:]


history = model.fit(partial_x_train, partial_y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)

1 个答案:

答案 0 :(得分:0)

这些行中有错误

y_val = train_data[:10000]
partial_y_train = train_data[10000:]

但是本教程说应该

y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]

train_data代表每个书面评论,而train_labels代表评论是正面还是负面。您希望模型在书面评论为正面或负面时学习。