文本数据处理:从独热编码到词嵌入
1. 独热编码
1.1 词和字符的独热编码
独热编码是将标记转换为向量的最常见、最基本的方法。它的原理是为每个单词关联一个唯一的整数索引,然后将这个整数索引 i 转换为大小为 N (词汇表大小)的二进制向量,除了第 i 个元素为 1 外,其余元素均为 0。
以下是词级别的独热编码的示例代码:
import numpy as np
samples = ['The cat sat on the mat.', 'The dog ate my homework.']
token_index = {}
for sample in samples:
for word in sample.split():
if word not in token_index:
token_index[word] = len(token_index) + 1
max_length = 10
results = np.zeros(shape=(len(samples),
max_length,
max(token_index.values()) + 1))
for i, sample in enumerate(samples):
for j, word in list(enumerate(sample.split()))[:max_length]:
超级会员免费看
订阅专栏 解锁全文
577

被折叠的 条评论
为什么被折叠?



