我正在尝试在 Keras 中进行多类分类。我正在使用众 包数据集。下面是我的代码:
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import numpy as np
from sklearn.preprocessing import LabelEncoder
from keras.models import Sequential
from keras.layers import Embedding, Flatten, Dense
from sklearn.preprocessing import LabelEncoder
df=pd.read_csv('text_emotion.csv')
df.drop(['tweet_id','author'],axis=1,inplace=True)
df=df[~df['sentiment'].isin(['empty','enthusiasm','boredom','anger'])]
df = df.sample(frac=1).reset_index(drop=True)
labels = []
texts = []
for i,row in df.iterrows():
texts.append(row['content'])
labels.append(row['sentiment'])
tokenizer = Tokenizer()
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences)
encoder = LabelEncoder()
encoder.fit(labels)
encoded_Y = encoder.transform(labels)
labels = np.asarray(encoded_Y)
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
indices = np.arange(data.shape[0])
np.random.shuffle(indices)
data = data[indices]
labels = labels[indices]
print labels.shape
model = Sequential()
model.add(Embedding(40000, 8,input_length=37))
model.add(Flatten())
model.add(Dense(100,activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(9, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(data,labels, validation_split=0.2, epochs=150, batch_size=100)
我收到此错误:
ValueError: Error when checking target: expected dense_3 to have shape (9,) but got array with shape (1,)
有人可以指出我的逻辑错误吗?我知道我的问题有点类似于Exception: Error when checks model target: expected dense_3 to have shape (None, 1000) but got array with shape (32, 2)
但我还没有设法找到错误。