python - 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 模型?
解决方案
完全一样。完全没有区别。
将句子转换为索引向量并进行拟合。
重要的事情:
不要以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]
]
推荐阅读
- react-native - 如果缓存数据与新的 reducers 结构不一致,我们如何防止移动应用程序崩溃?
- java - 使用 Keycloak 保护 Swagger 3
- javascript - 如何将变量从php返回到javascript
- amazon-web-services - 从 Extendscript 调用 Amazon Lambda(或获取 Amazon Lambda 的 http 调用 url)
- macos - 在不需要时杀死所有 Adobe 后台进程 MAC
- c++ - 扩展包含 lambda 类型的参数包时出现奇怪的错误
- database - Android房间数据库插入/更新序列
- haskell - 如何为这个特定结构实现 foldr?
- css - 标头中的 Jekyll 代码块太小
- reactjs - React 限制渲染次数以防止无限循环...重新渲染次数过多