【深度学习API】TensorFlow - tf.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)))

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于深度学习的语音识别的代码示例: ```python import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D # 加载数据集 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # 将数据集转换为张量 x_train = tf.expand_dims(x_train, axis=-1) x_test = tf.expand_dims(x_test, axis=-1) # 将标签转换为 one-hot 编码 y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) # 定义模型 model = Sequential([ Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((2,2)), Conv2D(64, (3,3), activation='relu'), MaxPooling2D((2,2)), Conv2D(64, (3,3), activation='relu'), Flatten(), Dense(64, activation='relu'), Dropout(0.5), Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test)) # 评估模型 model.evaluate(x_test, y_test) ``` 这个示例代码使用了卷积神经网络(CNN)来识别手写数字图像。代码使用的是 TensorFlow 框架,并使用了 Keras API 来构建模型。模型包含了多个卷积层、池化层、全连接层和 Dropout 层。在训练过程中,使用了交叉熵作为损失函数,使用了 Adam 优化器进行模型优化。最后,使用测试集对模型进行了评估。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值