tensorflow如何将one_hot标签和数字(整数)标签进行相互转化

 更新时间:2023年06月25日 10:36:21   作者:无敌右脑  
这篇文章主要介绍了tensorflow如何将one_hot标签和数字(整数)标签进行相互转化问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

将one_hot标签和数字(整数)标签进行相互转化

tensorflow自带one_hot标签函数

tensorflow 有封装好的函数可以直接将整数标签转化为one_hot标签

import tensorflow as tf 
label = [1,0,2,3,0]
y = tf.one_hot(label, depth=4).numpy()    
#使用ont_hot返回的是tensor张量,再用numpy取出数组
print(y)

得到:

[[0. 1. 0. 0.]
[1. 0. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[1. 0. 0. 0.]]

将one-hot转化为数字标签

将one-hot转化为数字标签没有封装好的函数,可以遍历并使用soft argmax取出整数:

label = [np.argmax(i) for i in y] 
print(label)

得到:

[1, 0, 2, 3, 0]

tensorflow中one_hot讲解以及多分类标签与one-hot转换

TensorFlow的one-hot函数讲解

import tensorflow as tf
tf.one_hot(indices, depth, on_value, off_value, axis)

indices是一个列表,指定张量中独热向量的独热位置,或者说indeces是非负整数表示的标签列表。len(indices)就是分类的类别数。

tf.one_hot返回的张量的阶数为indeces的阶数+1。

当indices的某个分量取-1时,即对应的向量没有独热值。

  • depth是每个独热向量的维度
  • on_value是独热值
  • off_value是非独热值

axis指定第几阶为depth维独热向量,默认为-1,即,指定张量的最后一维为独热向量

例如:对于一个2阶张量而言,axis=0时,即,每个列向量是一个独热的depth维向量

axis=1时,即,每个行向量是一个独热的depth维向量。axis=-1,等价于axis=1

import tensorflow as tf
# 得到4个5维独热行向量向量,
#    其中第1个向量的第0个分量是独热1,
#    第2个向量的第2个分量是独热,
#    第3个向量没有独热,因为指定为-1
#    第4个向量的第1个分量为独热
# labels向targets的转变
labels = [0, 2, -1, 1]
# labels是shape=(4,)的张量。则返回的targets是shape=(len(labels), depth)张量。
# 且这种情况下,axis=-1等价于axis=1
targets = tf.one_hot(indices=labels, depth=5, on_value=1.0, off_value=0.0, axis=-1)
with tf.Session() as sess:
    print(sess.run(targets))
[[ 1.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]]
# 得到1个5维独热行向量。
targets = tf.one_hot(indices=3, depth=5, on_value=1.0, off_value=0.0, axis=0)
with tf.Session() as sess:
     print(sess.run(targets))
[ 0.  0.  0.  1.  0.]
# 得到1个5维独热列向量
targets = tf.one_hot(indices=[3], depth=5, on_value=1.0, off_value=0.0, axis=0)
with tf.Session() as sess:
     print(sess.run(targets))
[[ 0.]
[ 0.]
[ 0.]
[ 1.]
[ 0.]]
targets = tf.one_hot(indices=[[0,1],[1,0]], depth=3)
with tf.Session() as sess:
    print(sess.run(targets))
[[[ 1.  0.  0.]
  [ 0.  1.  0.]]
 [[ 0.  1.  0.]
  [ 1.  0.  0.]]]

注:indices如果是n阶张量,则返回的one-hot张量则为n+1阶张量

在实际神经网络的设计应用中,给定的labels通常是数字列表,以标识样本属于哪一个分类。类别数则是独热向量的维数。

# 得到分类的独热向量
targets = tf.one_hot(labels, num_classes)

TensorFlow 多分类标签转换成One-hot

在处理多分类问题时,将多分类标签转成One-hot编码是一种很常见的手段,以下即为Tensorflow将标签转成One-hot的tensor。以Mnist为例,如果标签为“3”,则One-hot编码为[0,0,0,1,0,0,0,0,0,0].

import tensorflow as tf  # version : '1.12.0'
NUM_CLASSES = 10 # 10分类
labels = [0,1,2,3] # sample label
batch_size = tf.size(labels) # get size of labels : 4
labels = tf.expand_dims(labels, 1) # 增加一个维度
indices = tf.expand_dims(tf.range(0, batch_size,1), 1) #生成索引
concated = tf.concat([indices, labels] , 1) #作为拼接
onehot_labels = tf.sparse_to_dense(concated, tf.stack([batch_size, NUM_CLASSES]), 1.0, 0.0) # 生成one-hot编码的标签

将稀疏矩阵转换成密集矩阵,其中索引在concated中,值为1.其他位置的值为默认值0.

方法1:

from sklearn.preprocessing import OneHotEncoder,LabelEncoder
a = ['A','B','A','C']
label_encoder=LabelEncoder()
label_value = label_encoder.fit_transform(a)
enc = OneHotEncoder()
one_hot=enc.fit_transform(label_value.reshape(-1,1))
one_hot.toarray()
array([[1., 0., 0.],
       [0., 1., 0.],
       [1., 0., 0.],
       [0., 0., 1.]])

方法2:

from sklearn.preprocessing import LabelBinarizer
encoder = LabelBinarizer()
one_hot = encoder.fit_transform(a)
print(one_hot)
array([[1, 0, 0],
       [0, 1, 0],
       [1, 0, 0],
       [0, 0, 1]])

方法3:

import numpy as np
def dense_to_one_hot(labels_dense, num_classes):
    """Convert class labels from scalars to one-hot vectors."""
    num_labels = labels_dense.shape[0]
    index_offset = np.arange(num_labels) * num_classes
    labels_one_hot = np.zeros((num_labels, num_classes))
    labels_one_hot.flat[index_offset+labels_dense.ravel()] = 1
    return labels_one_hot
labels_dense = np.array([0,1,2,3,4]) 
num_classes  = 5
one_hot = dense_to_one_hot(labels_dense,num_classes)
print(one_hot)
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]]

keras中多分类标签转换成One-hot

import numpy as np
from keras.utils import to_categorical
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 7]
data = array(data)
print(data)
# [1 2 3 4 5 6 7 8 9 7]
#有普通np数组转换为one-hot
one_hots = to_categorical(data)
print(one_hots)
# [[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
#  [ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
#  [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
#  [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
#  [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
#  [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
#  [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]
#  [ 0.  0.  0.  0.  0.  0.  0.  0.  1.  0.]
#  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
#  [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]]

one_hot 转数组

# 由one-hot转换为普通np数组
data = [argmax(one_hot)for one_hot in one_hots]
print(data)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 7]

总结

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

相关文章

  • python实现获取单向链表倒数第k个结点的值示例

    python实现获取单向链表倒数第k个结点的值示例

    这篇文章主要介绍了python实现获取单向链表倒数第k个结点的值,结合实例形式分析了Python针对单向链表的定义、遍历、传值、判断等相关操作技巧,需要的朋友可以参考下
    2019-10-10
  • Python实现windows自动关机功能

    Python实现windows自动关机功能

    这篇文章主要为大家详细介绍了如何使用Python实现windows自动关机功能,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下
    2025-01-01
  • 使用GitHub和Python实现持续部署的方法

    使用GitHub和Python实现持续部署的方法

    这篇文章主要介绍了使用GitHub和Python实现持续部署的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • Python实现手写一个类似django的web框架示例

    Python实现手写一个类似django的web框架示例

    这篇文章主要介绍了Python实现手写一个类似django的web框架,结合具体实例形式分析了Python自定义简单控制器、URL路由、视图模型等功能,实现类似Django框架的web应用相关操作技巧,需要的朋友可以参考下
    2018-07-07
  • python 编码规范整理

    python 编码规范整理

    这篇文章主要介绍了python 编码规范整理,需要的朋友可以参考下
    2018-05-05
  • 深入解读python字符串函数

    深入解读python字符串函数

    这篇文章主要为大家介绍了python字符串函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-12-12
  • 跟老齐学Python之使用Python操作数据库(1)

    跟老齐学Python之使用Python操作数据库(1)

    本文详细讲述了使用python操作数据库所需要了解的知识以及准备工作,十分的详尽,这里推荐给想学习python的小伙伴。
    2014-11-11
  • 使用python和pygame绘制繁花曲线的方法

    使用python和pygame绘制繁花曲线的方法

    本篇文章主要介绍了使用python和pygame绘制繁花曲线的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • 利用Python进行数据可视化常见的9种方法!超实用!

    利用Python进行数据可视化常见的9种方法!超实用!

    这篇文章主要给大家介绍了关于利用Python进行数据可视化常见的9种方法!文中介绍的方法真的超实用!对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • 弄懂这56个Python使用技巧(轻松掌握Python高效开发)

    弄懂这56个Python使用技巧(轻松掌握Python高效开发)

    这篇文章主要介绍了弄懂这56个Python使用技巧(轻松掌握Python高效开发),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-09-09

最新评论