【问题标题】:Softmax layer in Keras returns a vector of 1sKeras 中的 Softmax 层返回一个 1s 的向量
【发布时间】:2017-10-16 13:31:24
【问题描述】:

我想在 Keras 中构建一个带有 softmax 层作为输出的 CNN,但我只得到这个作为输出:

[[[[ 1.]
   [ 1.]
   [ 1.]]]]

我的模型是这样构建的:

model = Sequential()
model.add(Conv2D(2, (1,3), padding='valid',
             input_shape=(3,3,50), init='normal', data_format='channels_first'))
model.add(Activation('relu'))
model.add(Conv2D(20, (1,48), init='normal', data_format='channels_first'))
model.add(Activation('relu'))
model.add(Conv2D(1, (1, 1), init='normal', data_format='channels_first', activation='softmax'))

我真的不明白,为什么 softmax 不起作用。可能是因为输入形状错误?

【问题讨论】:

    标签: python keras softmax


    【解决方案1】:

    softmax 激活将应用于最后一个轴。

    看看你的model.summary(),你的输出形状是(None, 3, 3, 1)

    在最后一个轴上只有一个元素,你的 softmax 输出确实总是 1。

    您必须选择要对哪个轴求和 1,然后正确地重塑输出。例如,如果您希望 softmax 考虑 3 个通道,则需要将这些通道移动到最终位置:

    #your last convolutional layer, without the activation: 
    model.add(Conv2D(3, (1, 1), kernel_initializer='normal', data_format='channels_first'))
    
    #a permute layer to move the channels to the last position:
    model.add(Permute((2,3,1)))
    
    #the softmax, now considering that channels sum 1.
    model.add(Activation('softmax'))
    

    但如果您的目的是整个结果的总和为 1,那么您应该添加 Flatten() 而不是 Permute()


    Keras 似乎更适合使用 channels_last。在这种情况下,softmax 将自动应用于通道,而不需要额外的工作。

    【讨论】:

      【解决方案2】:

      您的模型架构有问题。如果您查看一些流行的模型:

      您会发现 CNN 的结构通常如下所示:

      1. 一些带有 relu 激活的卷积层
      2. 池化层(即最大池化、平均池化等)
      3. 扁平化卷积层
      4. 致密层
      5. 然后,一个softmax

      将 softmax 应用于卷积层是没有意义的。

      【讨论】:

      • 谢谢,我尝试在卷积层之后添加一个密集层,但没有将其展平。现在可以了!
      • 卷积层(通道求和 1)中的 Softmax 是图像分割任务的好主意,其中每个通道都是一个类。
      • 对于像素分类,Uber 似乎在他们的最后一个卷积层中使用了 softmax:eng.uber.com/coordconv。我正在使用开源 Keras 实现。展平还会保留空间坐标信息吗?
      猜你喜欢
      • 1970-01-01
      • 2018-08-16
      • 2019-04-16
      • 2019-02-25
      • 2012-02-18
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多