这个有10个节点的网络的输出层如何对应一个整数呢?

How does the output layer of this network which has 10 nodes correspond to an integer?

ffnn = Sequential([
    Flatten(input_shape=X_train.shape[1:]),
    Dense(512, activation='relu'),
    Dropout(0.2),
    Dense(512, activation='relu'),
    Dropout(0.2),
    Dense(10, activation='softmax')
])
ffnn_history = ffnn.fit(X_train,
                        y_train,
                        batch_size=batch_size,
                        epochs=epochs,
                        validation_split=0.2,
                        callbacks=[checkpointer, early_stopping],
                        verbose=1,
                        shuffle=True)
ffnn_accuracy = ffnn.evaluate(X_test, y_test, verbose=0)[1]

这些代码来自https://github.com/stefan-jansen/machine-learning-for-trading/blob/main/18_convolutional_neural_nets/02_digit_classification_with_lenet5.ipynb

我了解这个网络以及 softmax 函数的工作原理。我的问题是,输出层有 10 个节点。输出应该是一个长度为 10 的向量(向量之和为 1)。它在训练和评估过程中如何匹配标签y,其中y是一个整数(它不是应该先将输出向量转换为相应的整数)吗?

tensorflow 会自动将长度为 10 的输出向量解释为相应的整数还是什么?

在你的例子中,标签是由损失函数 sparse_categorical_crossentropy():

单热编码的
>>> y_true = [1, 2]
>>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
>>> tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred).numpy()
array([0.05129344, 2.3025851 ], dtype=float32)

输出softmax(x)可以解释为概率分布(Σ softmax(x) = 1.0)。所以例如argmax(softmax(x)) = id_maxprob 会 return 你最有可能 class 的索引。

因此,您的神经网络目标向量将是 10 维的,这样每个整数 [0, 1, .., 8, 9] 对应于 softmax 输出的一个节点。

话虽这么说,您要预测的目标向量将简单地进行单热编码:

[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]  # == 0
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]  # == 1
..
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]  # == 9

换句话说:如果你有一批 images 并将其提供给你的网络,输出将是 (n, num_classes)(这里 num_classes 是 10)并且它是 you 谁将对输出进行最终解释 e.g.使用 np.argmax 以获得最终预测。

predictions = model(images)
predicted_ids = np.argmax(predictions, axis=1)

# Print each index == predicted integer
print(predicted_ids)

另外,请注意以下示例:

>>> tf.one_hot([1, 2, 9], depth=10)
<tf.Tensor: shape=(3, 10), dtype=float32, numpy=
array([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]], dtype=float32)>