【问题标题】:Word2vec with Conv1D for text classification confusionWord2vec 和 Conv1D 用于文本分类混淆
【发布时间】:2018-08-09 11:11:14
【问题描述】:

我正在做文本分类,并计划使用 word2vec 词嵌入并将其传递给 Conv1D 层进行文本分类。我有一个dataframe,其中包含文本和相应的标签(情感)。我使用了 gensim 模块并使用 word2vec 算法来生成词嵌入模型。我使用的代码:

import pandas as pd
from gensim.models import Word2Vec
from nltk.tokenize import word_tokenize
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)

我打算使用 CNN 并使用这个词嵌入模型。但是我应该如何为我的 cnn 使用这个词嵌入模型呢?我应该输入什么?

我打算使用类似的东西(显然不是使用相同的超参数):

model = Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation='relu'))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))

有人可以帮助我并指出正确的方向吗?提前致谢。

【问题讨论】:

  • 您需要在嵌入层中加载 word2vec 权重,您还需要将单词转换为整数,以便嵌入层能够将每个单词转换为向量,为此 word2vec 有一个字典将每个单词映射到一个整数
  • @Kailegh 你能详细说明一下,最好用一些代码吗?感谢您闪电般的快速响应。
  • 啊哈哈我现在正在工作,如果没有其他人这样做,我今晚会给你一个详细的答案虽然我通常会自己下载单词嵌入文件而不是使用 gensim 文件,但是我不会有问题
  • @Kaleigh 你能告诉我你提到的不使用 gensim 的替代方法吗?谢谢
  • 我的回答对你有用吗?

标签: python keras conv-neural-network word2vec multiclass-classification


【解决方案1】:

抱歉回复晚了,希望对你还是有用的。 根据您的应用程序,您可能需要下载特定的嵌入文件,例如这里您有 Glove files

EMBEDDING_FILE='glove.6B.50d.txt'

embed_size = 50 # how big is each word vector
max_features = 20000 # how many unique words to use (i.e num rows in embedding vector)
maxlen = 100 # max number of words in a comment to use

word_index = tokenizer.word_index
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))
for word, i in word_index.items():
    if i >= max_features: continue
    embedding_vector = embeddings_index.get(word)
    if embedding_vector is not None: embedding_matrix[i] = embedding_vector

#this is how you load the weights in the embedding layer
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp)

我从Jeremy Howard获取了这段代码,我想这就是你所需要的,如果你想加载其他文件,过程非常相似,通常你只需要更改加载文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2023-03-21
    • 2020-10-08
    • 2020-08-21
    • 1970-01-01
    • 2021-01-19
    • 2016-11-28
    • 2018-09-13
    相关资源
    最近更新 更多