代码之家  ›  专栏  ›  技术社区  ›  SRobertJames

在Tensorflow和Keras的两个通道上生成softmax

  •  0
  • SRobertJames  · 技术社区  · 7 年前

    (U, C) 哪里 C

    例如,如果 U=2 C=3 [ [1 2 3], [10 20 30] ] ,我希望输出完成 softmax(1, 2, 3) 对于通道0和 softmax(10, 20, 30) 第一频道。

    更新

    还请解释如何确保损失是两个交叉熵的总和,以及我如何验证这一点(也就是说,我不希望优化器只针对其中一个softmax的损失进行训练,而是针对每个softmax的交叉熵损失总和进行训练)。该模型使用Keras的内置 categorical_crossentropy 因为损失。

    2 回复  |  直到 7 年前
        1
  •  1
  •   today    7 年前

    定义一个 Lambda 分层并使用 softmax

    from keras import backend as K
    from keras.layers import Lambda
    
    soft_out = Lambda(lambda x: K.softmax(x, axis=my_desired_axis))(input_tensor)
    

    N维的numpy数组的形状为 (d1, d2, d3, ..., dn) . 它们中的每一个都称为轴。因此,第一个轴(即。 axis=0 )有维度 d1 ,第二个轴(即。 axis=1 d2 等等此外,阵列的最常见情况是2D阵列或形状为的矩阵 (m, n) m 轴=0 n 列(即。 轴=1

    >>> import numpy as np
    >>> a = np.arange(12).reshape(3,4)
    >>> a
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    
    >>> a.shape
    (3, 4)   # three rows and four columns
    
    >>> np.sum(a, axis=0)  # compute the sum over the rows (i.e. for each column)
    array([12, 15, 18, 21])
    
    >>> np.sum(a, axis=1)  # compute the sum over the columns (i.e. for each row)
    array([ 6, 22, 38])
    
    >>> np.sum(a, axis=-1) # axis=-1 is equivalent to the last axis (i.e. columns)
    array([ 6, 22, 38])
    

    现在,在您的示例中,计算softmax函数也适用同样的情况。必须首先确定要在哪个轴上计算softmax,然后使用 axis 论点此外,请注意,默认情况下,softmax应用于最后一个轴(即。 axis=-1 Activation 层,而不是:

    from keras.layers import Activation
    
    soft_out = Activation('softmax')(input_tensor)
    

    还有另一种方法是使用 Softmax 图层:

    from keras.layers import Softmax
    
    soft_out = Softmax(axis=desired_axis)(input_tensor)
    
        2
  •  2
  •   Mete Han Kahraman    7 年前

    https://keras.io/getting-started/functional-api-guide/

    input = Input(...)
    ...
    t = some_tensor
    t0 = t0[:,:,0]
    t1 = t0[:,:,1]
    soft0 = Softmax(output_shape)(t0)
    soft1 = Softmax(output_shape)(t1)
    outputs = [soft0,soft1]
    model = Model(inputs=input, outputs=outputs)
    model.compile(...)
    model.fit(x_train, [y_train0, ytrain1], epoch = 10, batch_size=32)
    
    推荐文章