如何从深度学习模型中获取神经元总数? Keras中有任何功能吗?
答案 0 :(得分:0)
您可以使用图层输出形状来计算Keras模型中神经元的数量。如果将一层的输出尺寸相乘,则可以获得该层中神经元的数量。当将其应用于所有有效层(具有神经元的层)并对神经元计数求和时,最终您将获得Keras模型中神经元的总数。这是代码:
def get_total_number_of_neurons(model, include_output_layer):
'''
Args:
model: Keras model
include_output_layer: A boolean parameter. Whether or not to include output layer's neurons into the calculation
Returns: number of neurons in the given model
'''
num_layers = len(model.layers)
total_num_of_neurons = 0
for layer_index in range(num_layers):
layer = model.layers[layer_index]
# since we multiply layer output dimensions, initial value is set to 1.
num_neurons_in_layer = 1
for i in range(1, len(layer.output.shape)):
try:
# when it is a valid layer to count neurons, an output dimension of the layer can be convertible to int.
num_neurons_in_layer *= int(layer.output.shape[i])
except Exception:
# if the output dimension of layer cannot be convertible to int,
# just pass that layer since it is not a valid layer to count neurons
pass
# if num_neurons_in_layer is not still 1, it means we have a valid layer to count neurons
if not num_neurons_in_layer == 1:
# when it is an output layer
if layer_index == (num_layers - 1):
if include_output_layer:
total_num_of_neurons += num_neurons_in_layer
else: # when it is not an output layer
total_num_of_neurons += num_neurons_in_layer
return total_num_of_neurons
我开始将第二个维度的输出维度相乘,如下部分所示:
range(1, len(layer.output.shape))
原因是图层输出的第一维是“ ?”,它表示您输入到模型中的样本数量,并且与模型中的神经元数量无关。因此,我们跳过了神经元数量计算的第一个维度。
我还添加了一个布尔参数 include_output_layer ,以便您可以选择是否在神经元计算数量中包括输出层。
最后,如果您不想包含输出层,则可以调用如下函数:
num_neurons = get_total_number_of_neurons(model= your_keras_model, include_output_layer= False)
或者,您可以在计算中包括输出层:
num_neurons = get_total_number_of_neurons(model= your_keras_model, include_output_layer= True)
希望这会有所帮助!