我对 Tensorflow 不熟悉,但经过一些测试,这是我发现的:
tf.one_hot() 采用 indices 和 depth。 indices 是实际转换为 one-hot 编码的值。 depth 指的是要使用的最大值。
以如下代码为例:
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(),depth 参数应该等于数组中存在的最大值,+1 表示 0。在这种情况下,最大值为 3 ,因此编码中有四个可能的值 - 0、1、2 和 3。因此,在 one-hot 编码中表示所有这些值需要 4 的深度。
至于转换为 numpy,如上所示,使用 Tensorflow 会话,在张量上运行 eval() 会将其转换为 numpy 数组。具体方法请参考How can I convert a tensor into a numpy array in TensorFlow?。
我不熟悉 Tensorflow,但我希望这会有所帮助。
注意:对于 MNIST,深度为 10 就足够了。