one-hot编码

one-hot介绍:

       又称独热编码、一位有效编码。其方法是使用N位状态寄 存器来对N个状态进行编码,每个状态都有它独立的寄存器位,并且在 任意时候,其中只有一位有效。

one-hot的应用:

        one hot在特征提取上属于词袋模型(bag of words)。例如我们的语料库中有段话:我毕业于湖南工业大学我就职于长沙代码研究所,以下是对该段话进行的分词流程:

1.我们首先对语料库分词,并获取其中所有的词,然后对每个词进行编号:

'我': 1, '毕业': 2, '于': 3, '湖南工业大学': 4, '就职': 5, '长沙代码研究所': 6

2.然后使用one hot对每段话提取特征向量

3.最终得到特征向量

下面是one-hot编码实现

import numpy as np
samples = ['我 毕业 于 湖南工业大学', '我 就职 于 长沙代码研究所']

token_index = {}
for sample in samples:
    for word in sample.split():
        if word not in token_index:
            token_index[word] = len(token_index) + 1

print(len(token_index))

print(token_index)

results = np.zeros(shape=(len(samples), len(token_index) + 1, max(token_index.values()) + 1))
results.shape

for i, sample in enumerate(samples):
    for j, word in list(enumerate(sample.split())):
        index = token_index.get(word)
        print(j, index, word)
        results[i ,j, index] = 1


print("\n\n打印results\n\n")
print(results)

results2 = np.zeros(shape=(len(samples), max(token_index.values()) + 1))

for i, sample in enumerate(samples):
    for _,word in list(enumerate(sample.split())):
        index = token_index.get(word)
        results2[i, index] = 1

print("\n\n打印results2\n\n")
print(results2)

运行结果截图:

基于keras实现:

from keras.preprocessing.text import Tokenizer
samples = ['我 毕业 于 湖南工业大学', '我 就职 于 长沙代码研究所']

#构建单词索引
tokenizer = Tokenizer()
tokenizer.fit_on_texts(samples)

word_index = tokenizer.word_index
print(word_index)
print(len(word_index))


sequences = tokenizer.texts_to_sequences(samples)
print(sequences)

one_hot_results = tokenizer.texts_to_matrix(samples)
print(one_hot_results)

运行结果截图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值