检查目标时:预期 dense_2 具有形状 (1,) 但得到形状为 (2,) 的数组

when checking target: expected dense_2 to have shape (1,) but got array with shape (2,)

csv 的情感分析包含 45k 和两个 cols[文本,情感],试图将 sigmoid 与 binary_crossentropy 一起使用,但它的 return 是一个错误:

Error when checking target: expected dense_2 to have shape (1,) but got array with shape (2,)

我曾尝试使用 LabelEncoder,但它 return 的输入形状不佳,我如何让编码标签为 Sigmond 1 dense 所接受?

#I do aspire here to have balanced classes
num_of_categories = 45247
shuffled = data.reindex(np.random.permutation(data.index))
e = shuffled[shuffled['sentiment'] == 'POS'][:num_of_categories]
b = shuffled[shuffled['sentiment'] == 'NEG'][:num_of_categories]
concated = pd.concat([e,b], ignore_index=True)
for idx,row in data.iterrows():
    row[0] = row[0].replace('rt',' ')
#Shuffle the dataset
concated = concated.reindex(np.random.permutation(concated.index))
concated['LABEL'] = 0

#encode the lab
encoder = LabelEncoder()
concated.loc[concated['sentiment'] == 'POS', 'LABEL'] = 0
concated.loc[concated['sentiment'] == 'NEG', 'LABEL'] = 1
print(concated['LABEL'][:10])
labels = encoder.fit_transform(concated)
print(labels[:10])
if 'sentiment' in concated.keys():
    concated.drop(['sentiment'], axis=1)

n_most_common_words = 8000
max_len = 130
tokenizer = Tokenizer(num_words=n_most_common_words, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)
tokenizer.fit_on_texts(concated['text'].values)
sequences = tokenizer.texts_to_sequences(concated['text'].values)
word_index = tokenizer.word_index

LabelEncoder的输出如果也是1dim,我猜你的网络输出有2dim。所以你需要 one-hot 你的 y_true.

使用

labels = keras.utils.to_categorical(concated['LABEL'], num_classes=2)

改为

labels = encoder.fit_transform(concated)