文本数据处理与词嵌入技术详解
1. 词和字符的独热编码
独热编码(One-hot encoding)是将标记转换为向量的最常见、最基本的方法。它的工作原理是为每个单词关联一个唯一的整数索引,然后将这个整数索引 $i$ 转换为大小为 $N$(词汇表大小)的二进制向量,除了第 $i$ 个条目为 1 外,其余条目均为 0。
下面是使用 Python 实现词级和字符级独热编码的示例代码:
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]:
index = t
超级会员免费看
订阅专栏 解锁全文
1147

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



