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

作者:强殖装甲凯普 时间:2022-01-05 07:09:55 

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

标签:python,label,one-hot
0
投稿

猜你喜欢

  • 对Python函数设计规范详解

    2023-08-02 15:59:17
  • python pyaudio音频录制的实现

    2022-03-13 08:44:31
  • python爬取微信公众号文章图片并转为PDF

    2021-02-02 06:53:31
  • php牛逼的面试题分享

    2023-11-20 19:31:35
  • Keras保存模型并载入模型继续训练的实现

    2021-08-12 23:23:32
  • python数据拟合之scipy.optimize.curve_fit解读

    2021-05-27 01:48:49
  • Python中实现单例模式的n种方式和原理

    2021-01-07 20:45:58
  • 使用MySQL数据库的23个注意事项

    2010-03-18 15:46:00
  • 如何判断URL格式是否符合规范?

    2010-01-12 20:14:00
  • Python folium的实用功能详解

    2021-08-27 10:07:21
  • C#调用python.exe使用arcpy方式

    2021-03-30 05:41:13
  • Python异常继承关系和自定义异常实现代码实例

    2023-06-22 07:34:44
  • Python3.9新特性详解

    2023-03-26 21:56:16
  • (X)HTML Strict 下的嵌套规则

    2008-03-08 18:39:00
  • 在Python 字典中一键对应多个值的实例

    2023-07-25 23:45:02
  • Python合并字典键值并去除重复元素的实例

    2022-02-10 17:48:40
  • python 自动化偷懒的四个实用操作

    2023-11-19 08:49:48
  • 也谈用户体验

    2009-07-15 12:56:00
  • PyTorch如何创建自己的数据集

    2022-10-17 05:22:17
  • Python 调用VC++的动态链接库(DLL)

    2023-06-19 09:01:44
  • asp之家 网络编程 m.aspxhome.com