TensorFlow – 如何创建一个热张量
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
一个热张量是一个张量,其中 i =j 和 i!=j 的索引处的所有值都相同。
Method Used:
- one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified.
示例 1:
Python3
# importing the library
import tensorflow as tf
# Initializing the Input
indices = tf.constant([1, 2, 3])
# Printing the Input
print("Indices: ", indices)
# Generating one hot Tensor
res = tf.one_hot(indices, depth = 3)
# Printing the resulting Tensors
print("Res: ", res )
Python3
# importing the library
import tensorflow as tf
# Initializing the Input
indices = tf.constant([1, 2, 3])
# Printing the Input
print("Indices: ", indices)
# Generating one hot Tensor
res = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1)
# Printing the resulting Tensors
print("Res: ", res )
输出:
Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res: tf.Tensor(
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]], shape=(3, 3), dtype=float32)
示例 2:此示例明确定义了一个热张量的 on 和 off 值。
Python3
# importing the library
import tensorflow as tf
# Initializing the Input
indices = tf.constant([1, 2, 3])
# Printing the Input
print("Indices: ", indices)
# Generating one hot Tensor
res = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1)
# Printing the resulting Tensors
print("Res: ", res )
输出:
Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
Res: tf.Tensor(
[[-1 3 -1]
[-1 -1 3]
[-1 -1 -1]], shape=(3, 3), dtype=int32)