下面完整代码在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)

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

1153

被折叠的 条评论
为什么被折叠?



