独热编码 将单词映射到数字向量

# 代码 容易理解

import numpy as np

sence = "An apple a day keeps doctor away said the doctor this is a girl I love you"

print(len(sence.split()))


class Dictionary(object):
    def __init__(self):
        self.word2idx = {}  # 存放单词 对应的索引
        self.idx2word = []  # 放 唯一的 单词
        self.length = -1

    def add_word(self, word):
        if word not in self.idx2word:
            self.idx2word.append(word)
            self.word2idx[word] = self.length + 1  # 索引 从0开始
            self.length += 1
        return self.word2idx[word]  # 返回单词 对应索引

    def __len__(self):
        return len(self.idx2word)  # 返回单词的总长度

    def onehot_encoded(self, word):
        vec = np.zeros(self.length + 1)  # 返回 唯一单词总数 对应的 长度 0
        vec[self.word2idx[word]] = 1  # 单词所在长度 为1
        return vec


die = Dictionary()
for tok in sence.split():  # 添加完所有的词, 之后 才能输出所有的独热编码
    die.add_word(tok)
    # die.onehot_encoded(tok)


print(die.idx2word)
print(die.word2idx)
print(die.onehot_encoded(die.idx2word[0]))
print(die.onehot_encoded(die.idx2word[2]))
print(die.onehot_encoded("you"))

# 输出结果

17
['An', 'apple', 'a', 'day', 'keeps', 'doctor', 'away', 'said', 'the', 'this', 'is', 'girl', 'I', 'love', 'you']
{'An': 0, 'apple': 1, 'a': 2, 'day': 3, 'keeps': 4, 'doctor': 5, 'away': 6, 'said': 7, 'the': 8, 'this': 9, 'is': 10, 'girl': 11, 'I': 12, 'love': 13, 'you': 14}
[1. 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.]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值