python - 在 Keras 中进行文本分类时出错

标签 python nlp keras conv-neural-network word2vec

我正在 Keras 中进行文本分类。首先,我使用 Word2Vec 创建一个嵌入矩阵并将其传递到 Keras Embedding 层。然后我在其上运行 Conv1D 。这是dataset我在用。下面是我的代码:

from gensim.models import Word2Vec
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import numpy as np
from keras.models import Sequential
from keras.layers import Embedding,Flatten,Dense,Conv1D,MaxPooling1D,GlobalMaxPooling1D
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
import pandas as pd
from nltk.tokenize import word_tokenize


# def dataframe_to_list_of_words(df_name, col):
#   df = pd.read_csv(df_name)
#   lst = df[col].drop_duplicates().values.tolist()
#   tokenized_sents = [word_tokenize(i) for i in lst]
#   tokenized_sents_mod = [word for sublist in tokenized_sents for word in sublist]
#   return tokenized_sents_mod

# def convert_data_to_index(string_data, wv):
#     index_data = []
#     for word in string_data:
#         if word in wv:
#             index_data.append(wv.vocab[word].index)
#     return index_data

df=pd.read_csv('emotion_merged_dataset.csv')
texts=df['text']
labels=df['sentiment']

df_tokenized=df.apply(lambda row: word_tokenize(row['text']), axis=1)


model = Word2Vec(df_tokenized, min_count=1,size=300)
##############
embedding_matrix = np.zeros((len(model.wv.vocab), 300))
for i in range(len(model.wv.vocab)):
#     print(model.wv.index2word[i])
    embedding_vector = model.wv[model.wv.index2word[i]]
    if embedding_vector is not None:
        embedding_matrix[i] = embedding_vector
################
labels=df['sentiment']
encoder = LabelEncoder()
encoder.fit(labels)
encoded_Y = encoder.transform(labels)
labels_encoded= np_utils.to_categorical(encoded_Y)
#########################

maxlen=30
tokenizer = Tokenizer(3000)
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, maxlen=37)
############################
embeddings = Embedding(input_dim=embedding_matrix.shape[0], output_dim=embedding_matrix.shape[1],
                      weights=[embedding_matrix],trainable=False)
model=Sequential()
model.add(embeddings)
model.add(Conv1D(32,7,activation='relu'))
model.add(MaxPooling1D(5))
model.add(Conv1D(32,7,activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(labels_encoded.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(data, labels, validation_split=0.2, epochs=10, batch_size=100)

运行代码时出现以下错误:

Error when checking target: expected dense_1 to have shape (None, 8) but got array with shape (19283, 1)

有人可以帮我吗?

最佳答案

您已将标签编码为分类标签,但实际上并未使用其结果。变化:

model.fit(data, labels, validation_split=0.2, epochs=10, batch_size=100)

到...

model.fit(data, labels_encoded, validation_split=0.2, epochs=10, batch_size=100)

关于python - 在 Keras 中进行文本分类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109014/

相关文章:

python - 尝试通过 pip 安装 MySQL-python 时找不到 Visual C++ 2010 Redistributable

r - 处理 R 中带有变音符号的字符数

python - 计算文本相似度的最佳方法是什么?

tensorflow - Keras 'Tensor' 对象没有属性 'ndim'

python - 分页不接受字典作为数据 - 不可散列的类型

python - 消息实例在 Google 应用引擎邮件接收中没有属性 'read'

python - 从 keras dropout 层中提取 dropout mask?

python - 如何使用 tf.keras.layers 通过 Tensorflow conv2d 馈送批量图像序列

python - 使用 Flask 在本地主机中创建一个 Web 服务器

programming-languages - 对于编程语言来说,与 "natural language"的相似性是一个令人信服的卖点吗?