59

对于前馈网络 (FFN),很容易计算参数的数量。给定一个 CNN、LSTM 等,有没有一种快速的方法来查找 keras 模型中的参数数量?

4

4 回答 4

118

模型和层为此目的有特殊的方法:

model.count_params()

此外,要获得每个图层尺寸和参数的简短摘要,您可能会发现以下方法很有用

model.summary()
于 2016-03-06T13:07:21.063 回答
14
import keras.backend as K

def size(model): # Compute number of params in a model (the actual number of floats)
    return sum([np.prod(K.get_value(w).shape) for w in model.trainable_weights])
于 2016-03-04T09:49:27.380 回答
4

追溯print_summary()函数,Keras 开发人员计算给定的可训练和不可训练参数的数量model如下:

import keras.backend as K
import numpy as np

trainable_count = int(np.sum([K.count_params(p) for p in set(model.trainable_weights)]))

non_trainable_count = int(np.sum([K.count_params(p) for p in set(model.non_trainable_weights)]))

鉴于K.count_params()定义为np.prod(int_shape(x)),此解决方案与 Anuj Gupta 的解决方案非常相似,除了使用set()和检索张量形状的方式。

于 2018-06-19T17:50:42.410 回答
0

创建网络后添加: model.summary
它将为您提供网络摘要和参数数量。

于 2021-06-09T03:13:33.487 回答