Numpy实现one-hot独热编码

本文介绍了一种实现One-hot编码的方法,并通过Python的NumPy和PyTorch库进行了测试。此外,还展示了如何在不同维度上进行数据填充操作,包括使用随机生成的数据进行示例演示。

下面完整代码在github仓库:传送门


一、实现one-hot编码并测试

import numpy as np
import torch


def one_hot(w, h, arr):
    z = np.zeros([w, h])  # 四行七列
    # print(z)

    for i in range(w):  # 4
        j = int(arr[i])  # 拿到数组里面的数字
        # print(j)
        z[i][j] = 1
    return z


if __name__ == '__main__':
    arr = np.array([2, 5, 6, 5])

    a = one_hot(len(arr), max(arr)+1, arr)
    # print(a)
    # print(a.argmax(1))

    label_onehot = torch.zeros(len(arr), max(arr) + 1)
    print(label_onehot.numpy())
    label_onehot[torch.arange(len(arr)), arr] = 1
    print(label_onehot.numpy().argmax(1))

    tensor = torch.tensor(arr, dtype=torch.long)
    tensor_out = torch.zeros(tensor.size(0), max(arr) + 1).scatter_(1, tensor.view(-1, 1), 1)
    print(tensor_out.numpy())
    print(tensor_out.numpy().argmax(1))

二、在多个维度里填充数据

import torch
import numpy as np

a = np.random.RandomState(0)
a = a.randn(3, 4)

x = torch.tensor(a, dtype=torch.float32)
print(x)

# 使用x的0轴的元素来填充y,tensor()里的值是x的0轴(行)元素对应的索引
# torch.tensor()里的两组索引对应x的0轴的前两个元素,里面的值是y的行索引
# 由于torch.tensor()的值是做索引,所以它的形状要和x保持一致。
y = torch.zeros(4, 4).scatter_(0, torch.tensor([[2, 0, 3, 1], [1, 0, 2, 0]]), x)
print(y)

z = torch.zeros(4, 10).scatter_(1, torch.tensor([[5], [8], [2], [3]]), 2)
print(z)

tensor = torch.tensor([5, 3, 8, 6])
print(tensor.view(-1, 1))
print(tensor.size(0))
print(torch.zeros(tensor.size(0), 10))

tensor_out = torch.zeros(tensor.size(0), 10).scatter_(1, tensor.view(-1, 1), 1)
print(tensor_out)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值