Search code examples
python-3.xencodingdeep-learningsentiment-analysistext-classification

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


sentiment analyses with csv contains 45k with two cols[text,sentiment],trying to use sigmoid with binary_crossentropy but its return an error :

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

i have tried to use LabelEncoder , but its return, bad input shape, how do i let the encoding label acceptable for 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

Solution

  • The output of LabelEncoder if also 1 dim, I guess the output of your network have two dim. So you need to one-hot your y_true.

    use

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

    instead

    labels = encoder.fit_transform(concated)