繁体   English   中英

Keras 致密层 Output 形状

[英]Keras Dense layer Output Shape

我无法理解获得第一个隐藏层的 output 形状背后的逻辑。 我举了一些随意的例子如下;

示例 1:

model.add(Dense(units=4,activation='linear',input_shape=(784,)))  
model.add(Dense(units=10,activation='softmax'))
model.summary()

Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_7 (Dense)              (None, 4)                 3140      
_________________________________________________________________
dense_8 (Dense)              (None, 10)                50        
=================================================================
Total params: 3,190
Trainable params: 3,190
Non-trainable params: 0

示例 2:

model.add(Dense(units=4,activation='linear',input_shape=(784,1)))   
model.add(Dense(units=10,activation='softmax'))
model.summary()
Model: "sequential_6"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_11 (Dense)             (None, 784, 4)            8         
_________________________________________________________________
dense_12 (Dense)             (None, 784, 10)           50        
=================================================================
Total params: 58
Trainable params: 58
Non-trainable params: 0

示例 3:

model.add(Dense(units=4,activation='linear',input_shape=(32,28)))    
model.add(Dense(units=10,activation='softmax'))
model.summary()
Model: "sequential_8"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_15 (Dense)             (None, 32, 4)             116       
_________________________________________________________________
dense_16 (Dense)             (None, 32, 10)            50        
=================================================================
Total params: 166
Trainable params: 166
Non-trainable params: 0

示例 4:

model.add(Dense(units=4,activation='linear',input_shape=(32,28,1)))    
model.add(Dense(units=10,activation='softmax'))
model.summary()
Model: "sequential_9"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_17 (Dense)             (None, 32, 28, 4)         8         
_________________________________________________________________
dense_18 (Dense)             (None, 32, 28, 10)        50        
=================================================================
Total params: 58
Trainable params: 58
Non-trainable params: 0

请帮助我理解逻辑。

另外,我认为input_shape=(784,)input_shape=(784,1)的等级相同,那么为什么它们的Output Shape不同?

According to the official documentation of Keras, for Dense layer when you give input as input_shape=(input_units,) the modal take as input arrays of shape (*, input_units) and outputs arrays of shape (*, output_units) [in your case input_shape=(784,)被视为input shape=(*, 784)并且 output 是output_shape=(*,4) ]

一般来说,对于(batch_size, ..., input_dim)的输入维度,模态会给出大小为(batch_size, ..., units)的 output。

因此,当您将输入作为input_shape=(784,)时,模态将作为输入 arrays 形状(*, 784) ,其中*是批量大小, 784作为 input_dim,将 output 形状作为(*, 4)

当输入为(784,1)时,模态将其视为(*, 784, 1)其中*是批量大小, 784...并且1是 input_dim => (batch_size, ..., input_dim)和output 为(*, 784, 4) => (batch_size, ..., units)

input_shape=(32,28)=>(*,32,28)也是如此,给出 output (*,32,4)input_shape=(32,28,1)=>(*,32,28,1)其中*是 batch_size, 32,28...1是 input_dim => (batch_size, ..., input_dim)

关于None是什么意思,请查看KERAS的model.summary中的“None”是什么意思?

逻辑很简单:dense layer独立应用于前一层的最后一个维度。 因此,形状为(d1, ..., dn, d)的输入通过具有m个单元的密集层会导致形状为(d1, ..., dn, m)的 output ,并且该层具有d*m+m个参数( m个偏差)。

请注意,相同的权重是独立应用的,因此您的示例 4 的工作原理如下:

for i in range(32):
    for j in range(28):
        output[i, j, :] = input[i, j, :] @ layer.weights + layer.bias

其中@是矩阵乘法。 input[i, j]是形状为(1,)的向量, layer.weights的大小为(1,4)layer.bias(1,)的向量。

这也解释了为什么(784,)(784,1)给出不同的结果:它们的最后一个维度是不同的,784 和 1。

密集层需要输入为(batch_size,input_size),大多数时候我们跳过batch_size并在训练期间定义它。

如果您的输入形状是一维的,在您的第一种情况下 (784,) model 将作为输入 arrays 形状 (~, 784) 和 Z78E6221F6393D1356681DB398F5399D8CZ 数组形状 ( 默认情况下,它将添加 4 的偏差(因为 4 个单位)。所以总参数将是

parameters -> 784*4 + 4 = 3140

如果您的输入形状是二维的,在第二种情况下 (784,1) model 将作为输入 arrays 形状 (784,1) 和 Z78E6221F6393D1356681DB398F1784CDZ 数组 (one)。 None是批次维度。 默认情况下,它将添加 4 的偏差(因为 4 个单位)。所以总参数将是

parameters -> 4(output units) + 4(bias) = 8

Output 层的形状取决于所用层的类型。 例如, Dense层的 output 形状基于层中定义的units ,其中卷积层的Conv形状取决于filters

要记住的另一件事是,默认情况下,任何输入的最后一个维度都被视为通道数。 在 output 形状估计的过程中,通道数被层中定义的units所取代。 对于像input_shape=(784,)这样的一维输入,最后使用,很重要。

示例 1(一维)、示例 2(二维,通道 =1)、示例 3(二维,通道 =28)和示例 4(3 维,通道 =1)。 如上所述,最后一个维度被Dense层中定义的units替换。

在这个stackoverflow答案中非常清楚地提到了有关维度、轴、通道、input_dim 等的更多细节。

keras 是一个高级别的 api,它处理了很多抽象。 以下示例可能会帮助您更好地理解。 在您的问题中,它是最接近 keras 抽象的原始 tensorflow 等效项:

import tensorflow as tf
from pprint import pprint


for shape in [(None,784,), (None, 784,1), (None, 32,28), (None, 32,28,1)]:
    shapes_list = []

    input_layer_1 = tf.compat.v1.placeholder(dtype=tf.float32, shape=shape, name=None)
    shapes_list.append(input_layer_1.shape)
    d1 = tf.compat.v1.layers.dense(
        inputs=input_layer_1, units=4, activation=None, use_bias=True, kernel_initializer=None,
        bias_initializer=tf.zeros_initializer(), kernel_regularizer=None,
        bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
        bias_constraint=None, trainable=True, name=None, reuse=None
    )
    shapes_list.append(d1.shape)
    d2 = tf.compat.v1.layers.dense(
        inputs=d1, units=10, activation=tf.compat.v1.nn.softmax, use_bias=True, kernel_initializer=None,
        bias_initializer=tf.zeros_initializer(), kernel_regularizer=None,
        bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
        bias_constraint=None, trainable=True, name=None, reuse=None
    )
    shapes_list.append(d2.shape)
    print('++++++++++++++++++++++++++')
    pprint(shapes_list)
    print('++++++++++++++++++++++++++')

Dense function 用于制作密集连接层或感知器

根据您的代码片段,您似乎已经创建了一个多层感知器(具有线性激活 function f(x)=x),其中隐藏层 1 有 4 个神经元,output 层为要预测的 10 个类/标签定制。

每层中的神经元数量由单位参数确定。 而 layer_L 中每个神经元的 Shape 由前一个layer_L-1output决定。

如果一个密集层的输入是(BATCH_SIZE, N, l) ,那么 output 的形状将是(BATCH_SIZE, N, value_passed_to_argument_units_in_Dense)

如果输入是(BATCH_SIZE, N, M, l) ,那么 output 形状是(BATCH_SIZE, N, M, value_passed_to_argument_units_in_Dense)等等。

笔记:

这仅在Dense神经元的情况下发生,因为它不会改变 batch_size 和 last_channel 之间的中间维度。

然而,在其他神经元如Conv2D->(Max/Avg)pooling的情况下,中间维度可能(取决于传递的 arguments)也会发生变化,因为这些神经元也作用于这些维度。

根据 keras

Dense layer is applied on the last axis independently. [1]

https://github.com/keras-team/keras/issues/10736#issuecomment-406589140

第一个例子:

input_shape=(784,)
model.add(Dense(units=4,activation='linear',input_shape=(784,)))

它说输入只有 784 行。model 的第一层有 4 个单元。 密集层中的每个单元都连接到所有 784 行。

这就是为什么

Output shape=  (None, 4) 

None 代表 batch_size,这里不知道。

第二个例子

这里输入 2 阶张量

input_shape=(784,1)
Units = 4

所以现在输入是 784 行和 1 列。 现在,密集层的每个单元都连接到总共 784 行中的每个元素中的 1 个元素。 Output 形状 =(无,784, 4)
没有批量大小。

第三个例子

 input_shape=(32,28)

现在每个密集层单元都连接到 32 行中的每一个的 28 个元素。 所以

output_shape=(None,32,4)

最后一个例子

model.add(Dense(units=4,activation='linear',input_shape=(32,28,1)))   

再次将密集层应用于最后一个轴,Output 形状变为

Output Shape =(None,32,28,4)

笔记

rank 在 (784,) 处为 1,逗号不代表另一个维度。 排名是 2 在 (784,1)

stackcoverflow帖子中的图表可以进一步帮助您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM