如何查找keras模型的参数数量?

Anu*_*pta 40 deep-learning keras

对于前馈网络(FFN),可以轻松计算参数数量.鉴于CNN,LSTM等有一种快速查找keras模型中参数数量的方法吗?

Ser*_*nko 78

模型和图层具有用于此目的的特殊方法:

model.count_params()
Run Code Online (Sandbox Code Playgroud)

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

model.summary()
Run Code Online (Sandbox Code Playgroud)


Anu*_*pta 13

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])
Run Code Online (Sandbox Code Playgroud)


Mig*_*rez 5

追溯该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)]))
Run Code Online (Sandbox Code Playgroud)

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