【深度学习API】TensorFlow - tf.one_hot()

本文深入解析了TensorFlow中tf.one_hot函数的作用与用法,包括如何将数据转换为one-hot编码格式,以及如何从one-hot编码还原回原始数组。通过实例演示了关键参数indices和depth的设置,并提供了代码示例,帮助读者理解和掌握one-hot编码在深度学习项目中的实际应用。
部署运行你感兴趣的模型镜像

tf.one_hot()

作用:转换为one-hot 编码格式,由于我们一般预测结尾使用softmax,导致结果全为one-hot形式,因此我们在做测试集时,需要将label转换为one-hot格式,或者将预测结果的one-hot格式转换为数组形式;

关键参数:indices , depth

indices: 传入tensor,如[1,0,3,2]

depth:one-hot的编码深度

代码示例:

    one = np.array([1,0,3,2])
    with tf.Session() as sess:

        sess.run(tf.global_variables_initializer())

        tensor_one = tf.convert_to_tensor(one)

        print(sess.run(tf.one_hot(tensor_one,depth=4)))

结果,数组里的值全部为one-hot编码格式里1的下标单位:

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

如果此时将depth = 3,就会发现,one-hot 无法编码超出的范围,具体见代码:

    one = np.array([1,0,3,2])
    with tf.Session() as sess:

        sess.run(tf.global_variables_initializer())

        tensor_one = tf.convert_to_tensor(one)

        print(sess.run(tf.one_hot(tensor_one,depth=3)))

结果,看到第三行就无法体现array[1,0,3,2]中的3,因此,depth 也就是array 的长度,平时可以使用depth = len(array):

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

 接下来,考虑one-hot  转array

我们使用tf.argmax()来转换:

tf.argmax详细使用见链接:tf.argmax使用,点我

接下来我们就将之前转换结果转换回来

代码:

    import numpy as np

    one = np.array([1,0,3,2])
    with tf.Session() as sess:

        sess.run(tf.global_variables_initializer())


        tensor_one = tf.convert_to_tensor(one)

        one_hot_res = tf.one_hot(tensor_one,depth=4)

        print(sess.run(tf.argmax(one_hot_res,0)))

结果如下:

        one_hot_res = tf.one_hot(tensor_one,depth=4)
        print(sess.run(tf.argmax(one_hot_res,0)))

 

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

``` !mkdir -p ~/.keras/datasets !cp work/mnist.npz ~/.keras/datasets/ import warnings warnings.filterwarnings("ignore") from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() print(f"训练数据形状: {train_images.shape}") print(f"训练标签长度: {len(train_labels)}") print(f"测试数据形状: {test_images.shape}") print(f"测试标签长度: {len(test_labels)}") from keras import models from keras import layers # 构建神经网络模型 network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) # 隐藏层:512个神经元,激活函数为ReLU network.add(layers.Dense(10, activation='softmax')) # 输出层:10个分类,激活函数为Softmax # 编译模型 network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # 数据预处理 train_images = train_images.reshape((60000, 28 * 28)) # 将图像展平成一维向量 train_images = train_images.astype('float32') / 255 # 归一化到[0,1] test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 # 标签编码 from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 训练模型 network.fit(train_images, train_labels, epochs=5, batch_size=128) # 测试模型性能 test_loss, test_acc = network.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)```W0402 08:09:22.415642 140410418362176 deprecation.py:323] From /opt/conda/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where W0402 08:09:22.484165 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. W0402 08:09:22.495126 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. W0402 08:09:22.537523 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:2741: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. W0402 08:09:22.546429 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. W0402 08:09:22.548026 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. W0402 08:09:22.566734 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. W0402 08:09:22.567799 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. W0402 08:09:22.613820 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead.
最新发布
04-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值