我正在尝试使用tensorflow构建mnist数据集的y_train的单热编码。我不明白该怎么做?
# unique values 0 - 9
y_train = array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
在keras
中,我们会做类似的事情
# this converts it into one hot encoding
one hot_encoding = tf.keras.utils.to_categorical(y_train)
在tf.one_hot
中,我应该向indices
和深度
参数输入什么?完成一次热编码后,如何将其从 2d-tensor 转换回 numpy 数组?
最佳答案
我不熟悉 Tensorflow,但经过一些测试,这是我发现的:
tf.one_hot()
接受一个索引
和一个深度
。 索引
是实际转换为one-hot编码的值。 深度
是指要利用的最大值。
例如,采用以下代码:
y = [1, 2, 3, 2, 1]
tf.keras.utils.to_categorical(y)
sess = tf.Session();
with sess.as_default():
print(tf.one_hot(y, 2).eval())
print(tf.one_hot(y, 4).eval())
print(tf.one_hot(y, 6).eval())
tf.keras.utils.to_categorical(y)
返回以下内容:
array([[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 1., 0., 0.]], dtype=float32)
相比之下,tf.one_hot()
选项(2、4 和 6)执行以下操作:
[[0. 1.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 1.]]
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 1. 0.]
[0. 1. 0. 0.]]
[[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]]
从这里可以看出,使用 tf.one_hot()
来模拟 tf.keras.utils.to_categorical()
,深度
参数应等于数组中存在的最大值,+1 表示 0。在本例中,最大值为 3,因此编码中有四个可能的值 - 0、1、2 和 3。因此,需要深度为 4 来表示 one-hot 编码中的所有这些值。
至于转换为 numpy,如上所示,使用 Tensorflow session ,在张量上运行 eval()
将其转换为 numpy 数组。有关执行此操作的方法,请参阅 How can I convert a tensor into a numpy array in TensorFlow? .
我不熟悉 Tensorflow,但希望这会有所帮助。
注意:对于 MNIST 而言,深度 10 就足够了。
关于python - 如何使用 tf.one_hot 计算一种热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56695125/