下面是一个简单的用Python实现的One-hot编码转换的例子:

def onehot_encode(word_list, vocab):
    '将单词列表word_list转换为onehot编码'
    :param word_list: 单词列表
    :param vocab: 词汇表,包含所有可能的单词
    :return: onehot编码矩阵
    onehot = []
    for word in word_list:
        # 创建一个全0的向量
        vec = [0] * len(vocab)
        if word in vocab:
            # 将单词所在位置设为1
            vec[vocab.index(word)] = 1
        onehot.append(vec)
    return onehot

# 测试
vocab = ['apple', 'banana', 'cherry']
word_list = ['apple', 'banana', 'cherry', 'orange']
onehot = onehot_encode(word_list, vocab)
print(onehot)

输出:

[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]

以上代码将单词列表['apple', 'banana', 'cherry', 'orange']转换为onehot编码矩阵,其中vocab是词汇表,包含所有可能出现的单词。在onehot编码矩阵中,每一行代表一个单词,向量的长度等于词汇表大小,向量中只有单词所在位置为1,其余位置均为0。在本例中,单词'orange'不在词汇表中,因此其对应的onehot向量为全0向量。

Python实现One-Hot编码转换:简单易懂的代码示例

原文地址: https://www.cveoy.top/t/topic/oTyc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录