文本单词one-hot编码

单词->字母->向量

神经网络是建立在数学的基础上进行计算的,因此对数字更敏感,不管是什么样的特征数据都需要以向量的形式喂入神经网络,无论是图片、文本、音频、视频都是一样。

one-hot编码,也就是独热编码,是一种常用的编码手段。在多分类识别的时候,喂入神经网络的标签就是独热码,比如手写数字识别一共有10个分类,某张图片标签是6,则独热码为:0 0 0 0 0 0 1 0 0 0

下面演示将一个单词进行ont-hot编码:

#字母表
word_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9,'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14,'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19,'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

#进行编码的单词
word = 'china'

#ont-hot编码
arr = np.zeros((len(word),len(word_id)))
for k,w in enumerate(word):
    arr[k][word_id[w]] = 1

print(arr)

打印结果:

[[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

文本->单词->向量

文本编码则与单词编码不同,单词编码以26个字母为映射字典,文本编码需要以单词为单位进行字典映射,因为单词是有语义的,在实际场景中往往捕捉的是文本所表达的意思,而不是文本本身的字母组成。

#要编码的文本
text = 'I am Chinese, I love China'
total_num = len(text.replace(',',' ').split())

#映射字典
word_id = {}
sentences = text.split(',')
for line in sentences:
    for word in line.split():
        if word not in word_id:
            word_id[word] = len(word_id)

print(word_id)

#ont-hot编码
arr = np.zeros((len(sentences),total_num,len(word_id)))
for k,v in enumerate(sentences):
    for kk,vv in enumerate(v.split()):
        arr[k][kk][word_id[vv]] = 1

print(arr)

打印结果:

{'I': 0, 'am': 1, 'Chinese': 2, 'love': 3, 'China': 4}
[[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]

[[1. 0. 0. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]

原文地址:https://www.cnblogs.com/fengyumeng/p/14222640.html