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

1,673 阅读3分钟

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编码的标签

sparse_to_dense 函数说明:www.tensorflow.org/api_docs/py…
将稀疏矩阵转换成密集矩阵,其中索引在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]

blog.csdn.net/ictcxq/arti…

blog.csdn.net/gqixf/artic…

blog.csdn.net/qq_33373858…

blog.csdn.net/Hero_Never_…

blog.csdn.net/u011311291/…

blog.csdn.net/ChaoFeiLi/a…

www.cnblogs.com/wxshi/p/776…