神经网络 - 无法理解输出层的行为

问题描述 投票:0回答:1

我想知道为什么它有效(查找注释“#这是输出层,这就是我正在谈论的”):

model = Sequential() # Not talking about this
model.add(Dense(32, activation='relu', input_dim = X_train.shape[1])) # Not talking about this
model.add(Dense(16, activation='relu')) # Not talking about this
model.add(Dropout(0.2)) # Not talking about this
model.add(Dense(16, activation='relu')) # Not talking about this
model.add(Dense(y_train.nunique()+1, activation='softmax')) # This is the output layer and this is what I am talking about
          
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(learning_rate = 0.01), metrics=['accuracy']) # Not talking about this
model.summary() # Not talking about this

而不是这个(查找注释“#这是输出层,这就是我正在谈论的”)::

model = Sequential() # Same as above
model.add(Dense(32, activation='relu', input_dim = X_train.shape[1])) # Same as above
model.add(Dense(16, activation='relu')) # Same as above
model.add(Dropout(0.2)) # Same as above
model.add(Dense(16, activation='relu')) # Same as above
model.add(Dense(y_train.nunique(), activation='softmax')) # This is the output layer and this is what I am talking about
          
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(learning_rate = 0.01), metrics=['accuracy']) # Same as above
model.summary() # Same as above

所以这里发生的是我有一个非常基本的神经网络,我用它来预测多类数据集。目标中有 10 个类,从 0 开始一直到 10(9 除外;9 不存在)。在我评论“#这是输出层,这就是我正在谈论的”的地方,当我将输出神经元的单位指定为目标的唯一值的数量(

y_train.nunique()
)时,它会抛出一个像这样的错误:

Detected at node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits defined at (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
...

  File "c:\<redacted>\Projects\<redacted>\Lib\site-packages\keras\src\backend.py", line 5775, in sparse_categorical_crossentropy

Received a label value of 10 which is outside the valid range of [0, 10).  Label values: 5 0 3 3 1 8 10 4 3 1 0 0 1 3 5 6 10 6 10 8 4 6 6 6 1 2 7 10 8 0 4 8
     [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_737445]

另一方面,当我给出的单位数量不止于此时,就像上面的例子中的那样,它是

y_train.nunique()+1
,它会经历所有 200 个时期。我不明白这是怎么回事。

还有,

  1. 输出层是否正确(对于相关类的数量)?
  2. 我对输出层的理解是否正确(对于这个特定问题,输出中的神经元数量必须等于目标的唯一值的数量(这也是数据所属的类))?
python keras deep-learning neural-network
1个回答
1
投票

是的,我明白你的问题。 输出层应等于目标类的数量。例如,在您的情况下,将输出神经元视为

y_train.nunique() is 10
,那么最终层输出和标签应在0 - 9的范围内。标签值10不会包含在该特定范围内。 所以它抛出错误接收到标签值10,该值超出了有效范围,因为标签10不会包含在最终的softmax神经元数量10中

上图将表示类别为3的softmax层。[0.9%是类别0,0.1%是类别1,0.0%是类别2]如果类别数为10,则将在softmax中创建10个类别概率。 在您的情况下,班级数量为 11。

如果

y_train.nunique() + 1 is 10
那么最终层输出和标签应该在 0 - 10 的范围内,对于第 10 个类,将创建概率 softmax。 所以代码可以正常工作。

所有类别概率的总和将为 1。缺少的 9 也将被视为一类

© www.soinside.com 2019 - 2024. All rights reserved.