【问题标题】:Vectorize list of string with Word2Vec to feed to keras sequential layer使用 Word2Vec 向量化字符串列表以馈送到 keras 顺序层
【发布时间】:2020-04-03 15:01:06
【问题描述】:

我正在尝试使用 fastText 构建一个定制的词嵌入模型,它将我的数据(句子列表)表示为向量,以便我可以将其“输入”到 Keras CNN 以进行滥用语言检测。

我的标记化数据存储在这样的列表中:

data = [['is',
      'this',
      'a',
      'news',
      'if',
      'you',
      'have',
      'no',
      'news',
      'than',
      'shutdown',
      'the',
      'channel'],
     ['if',
      'interest',
      'rate',
      'will',
      'hike',
      'by',
      'fed',
      'then',
      'what',
      'is',
      'the',
      'effect',
      'on',
      'nifty']]

我目前正在应用这样的 fastText 模型:

model = fastText(data, size=100, window=5, min_count=5, workers=16, sg=0, negative=5)

然后我执行:

model = FastText(sentences, min_count=1)

documents = []

for document in textList:
    word_vectors = []
    for word in document: 
        word_vectors.append(model.wv[word])
    documents.append(np.concatenate(word_vectors)

document_matrix = np.concatenate(documents)

显然,document_matrix 不适合作为我的 Keras 模型的输入:

from keras.models import Sequential
from keras import layers
from keras.layers import Dense, Activation

model = Sequential()
model.add(layers.Conv1D(filters=250, kernel_size = 4, padding = 'same', input_shape=( 1,))) 
model.add(layers.GlobalMaxPooling1D()) 
model.add(layers.Dense(250, activation='relu')) 
model.add(layers.Dense(3, activation='sigmoid')) 

我陷入困境,想不出如何使嵌入的输出适合 Keras 的输入。

提前非常感谢你们,你们是最棒的!

丽莎

【问题讨论】:

    标签: keras nlp tokenize word2vec fasttext


    【解决方案1】:

    您可以使用 model[YOURKEYWORD] 从 word2vec 模型中获取每个单词表示。您的 word2vec 模型中可能不存在某些词嵌入,因此您可以在代码中使用 try-catch

    【讨论】:

    • 嗨!非常感谢 !我切换到 FastText 以避免 OOV 问题并执行了以下操作:documents = [] for document in textList: word_vectors = [] for word in document: # 或您用于分隔标记的逻辑 word_vectors.append(model.wv[word]) files.append(np.concatenate(word_vectors)) document_matrix = np.concatenate(documents) 现在,矩阵的形状 (22938600,) 不适合 Sequential 的输入形状,你知道我能做什么吗?谢谢
    • 您能否根据此评论编辑您的问题。从您的评论中很难理解代码。
    猜你喜欢
    • 2020-08-19
    • 2019-03-12
    • 2012-09-05
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多