首页 > 解决方案 > LSTM如何将字符嵌入向量转换为句子向量进行句子分类?

问题描述

我想为使用字符嵌入的句子分类构建一个 LSTM 模型。

我知道如何使用词嵌入来做到这一点,模型可以从词索引中学习嵌入,但不确定如何使用字符嵌入来做到这一点。

对于词嵌入:

sentence_list = ['this is a dog', 'the cat and the mouse']
label = [1,0]
word_dict = {'this':1,
             'is':2,
             'a':3,
             'dog':4,
             'the':5,
             'cat':6,
             'and':7,
             'mouse':8}

# set vector length = 9
vectors = [[1,2,3,4,0,0,0,0,0]
              [0,0,0,0,5,6,7,5,8]]
model.fit(vectors,label)

因此可以将其安装到 LSTM 模型中。

我们如何处理基于字符的向量?

例如:如果我有这个字符字典:

 char_dict = {'t':1,
             'h':2,
             'i':3,
             's':4,
             'a':5,
             'd':6,
             'o':7,
             'g':8}

我如何将其格式化为 LSTM 分类模型可读?更具体地说,我们如何组合多个字符向量以输入 LSTM 模型?

标签: pythontensorflowkeraslstm

解决方案


完全一样。完全没有区别。

将句子转换为索引向量并进行拟合。

重要的事情

不要以0开头的句子,你vectors应该是:

vectors = [[1,2,3,4,0,0,0,0,0]
          [5,6,7,5,8,0,0,0,0]]

有空格(至少)和标点符号的索引:

 char_dict = {'t':1,
         'h':2,
         'i':3,
         's':4,
         'a':5,
         'd':6,
         'o':7,
         'g':8
         ' ':9,
         '.':10,
         'c':11}

sentences = ['this is a dog', 'that is a cat.']
vectors = [
              [char_dict[ch] for ch in sentence] for sentence in sentences
          ]

vectors = [
              [1, 2, 3, 4, 9, 3, 4, 9, 5,  9, 6, 7,  8],
              [1, 2, 5, 1, 9, 3, 4, 9, 5, 11, 5, 1, 10]
          ]

推荐阅读