python label与one-hot之间的互相转换方式

label与one-hot之间的互相转换

有时候需要label,比如强化学习的离散动作空间,输出动作索引;有时候需要one-hot,比如训练数据或者输入上一个状态的动作,简单的互相转换还是重要的。

label 转 one-hot

通过 np.eye(action_dims)[actions] 快速生成:

>>> import numpy as np
>>> label = [1,2,2,3]
>>> np.eye(4)[label]
array([[0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])

one-hot 转label

numpy可以通过 np.argmax(onehot, 1) 实现,pytorch 可以通过 torch.topk(one_hot, 1)[1].squeeze(1) 实现:

>>> import torch
>>> onehot
array([[0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
>>> np.argmax(onehot,1)
array([1, 2, 2, 3], dtype=int64)
>>> torch.topk(torch.tensor(onehot), 1)[1].squeeze(1)
tensor([1, 2, 2, 3])

label:one-hot 与 标量转化

标量 转化为 one-hot 向量

from keras.utils import to_categorical

data = [1, 3, 2, 0, 3, 2, 2, 1, 0, 1]
encoded = to_categorical(data)
print("encoded:", encoded)

输出:

encoded: [[0. 1. 0. 0.]

[0. 0. 0. 1.]

[0. 0. 1. 0.]

[1. 0. 0. 0.]

[0. 0. 0. 1.]

[0. 0. 1. 0.]

[0. 0. 1. 0.]

[0. 1. 0. 0.]

[1. 0. 0. 0.]

[0. 1. 0. 0.]]

one-hot向量 转化为 标量

因为一个热向量是一个包含0和1的向量,所以可以这样做:

encoded = np.array([[0, 1, 0, 0],
                    [0, 0, 0, 1],
                    [0, 0, 1, 0],
                    [1, 0, 0, 0],
                    [0, 0, 0, 1],
                    [0, 0, 1, 0],
                    [0, 0, 1, 0],
                    [0, 1, 0, 0],
                    [1, 0, 0, 0],
                    [0, 1, 0, 0]])

data = [np.where(r == 1)[0][0] for r in encoded]
print("data:", data)

输出:

data: [1, 3, 2, 0, 3, 2, 2, 1, 0, 1]

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/qq_38163755/article/details/125428293