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

TensorFlow的one_hot函数

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

one_hot(
indices, #指数的张量,即label的矩阵形式(1行 n列)
depth, #一个标量,用于定义一个 one hot 维度的深度。即分类数
on_value=None, #定义在 indices[j] = i 时填充输出的值的标量。(默认:1)
off_value=None, #定义在 indices[j] != i 时填充输出的值的标量。(默认:0
axis=None, #要填充的轴(默认:-1,一个新的最内层轴)
dtype=None, #输出张量的数据类型。
name=None
)
 

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 函数说明:https://www.tensorflow.org/api_docs/python/tf/sparse_to_dense
将稀疏矩阵转换成密集矩阵,其中索引在concated中,值为1.其他位置的值为默认值0.
 

方法1:
a = ['A','B','A','C']
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
label_value = label_encoder.fit_transform(a)
>>label_encoder.classes_
array(['A', 'B', 'C'], dtype='<U1')
>>label_value
array([0, 1, 0, 2], dtype=int64)
encoder = OneHotEncoder()
>>one_hot.toarray()
[[ 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)
>>one_hot
array([[1, 0, 0],
       [0, 1, 0],
       [1, 0, 0],
       [0, 0, 1]])
 
方法3:
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

 

keras中

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转换为普通np数组 data = [argmax(one_hot)for one_hot in one_hots] print(data) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 7]
 

https://blog.csdn.net/ictcxq/article/details/78545282

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好,我可以回答你的问题。以下是使用 TensorFlow 框架编写 LeNet 分类网络的代码示例: ```python import tensorflow as tf # 定义 LeNet 网络结构 def LeNet(x): # 第一层卷积层 conv1 = tf.layers.conv2d(inputs=x, filters=6, kernel_size=[5, 5], padding="valid", activation=tf.nn.relu) # 第一层池化层 pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # 第二层卷积层 conv2 = tf.layers.conv2d(inputs=pool1, filters=16, kernel_size=[5, 5], padding="valid", activation=tf.nn.relu) # 第二层池化层 pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # 将卷积层输出的特征图转换为一维向量 flatten = tf.layers.flatten(pool2) # 第一层全连接层 fc1 = tf.layers.dense(inputs=flatten, units=120, activation=tf.nn.relu) # 第二层全连接层 fc2 = tf.layers.dense(inputs=fc1, units=84, activation=tf.nn.relu) # 输出层 logits = tf.layers.dense(inputs=fc2, units=10) return logits # 定义输入占位符 x = tf.placeholder(tf.float32, [None, 32, 32, 1]) y = tf.placeholder(tf.int64, [None]) # 加载 MNIST 数据集 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=False) # 将数据集转换为 LeNet 所需的格式 x_train = mnist.train.images.reshape(-1, 28, 28, 1) y_train = mnist.train.labels x_test = mnist.test.images.reshape(-1, 28, 28, 1) y_test = mnist.test.labels # 定义损失函数和优化器 logits = LeNet(x) loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=logits) train_op = tf.train.AdamOptimizer().minimize(loss) # 定义评估指标 accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, axis=1), y), tf.float32)) # 训练模型 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(100): _, loss_val, acc_val = sess.run([train_op, loss, accuracy], feed_dict={x: x_train, y: y_train}) if i % 100 == : print("Step %d, loss = %.4f, accuracy = %.2f%%" % (i, loss_val, acc_val * 100)) test_acc = sess.run(accuracy, feed_dict={x: x_test, y: y_test}) print("Test accuracy = %.2f%%" % (test_acc * 100)) ``` 希望这个代码示例能够帮助到你。如果你有其他问题,欢迎继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值