实例化新模型后,Keras 模型的大小会增加

Size of a Keras model increases after a new model is instantiated

标题不言自明,玩具代码如下:

from pympler import asizeof 
from keras.models import Sequential
from keras.layers import Dense

model_1 = Sequential([
  Dense(1, activation='relu', input_shape=(10,)),
])

print('Model 1 size = ', asizeof.asizeof(model_1))

model_2 = Sequential([
  Dense(1, activation='relu', input_shape=(10,)),
])

print('Model 1 size = ', asizeof.asizeof(model_1))
print('Model 2 size = ', asizeof.asizeof(model_2))

Pympler 是一个 Python 内存分析器。代码的输出是:

Model 1 size =  68624
Model 1 size =  92728
Model 2 size =  92728

期望的输出是:

Model 1 size =  68624
Model 1 size =  68624
Model 2 size =  68624

Python version: Python 3.6.8

Keras version: 2.3.1

Tensorflow version: 2.1.0

我怀疑这是一个错误,如果这确实是一个错误,我会在他们的 Github 中提交一个问题。

在文档中 https://pympler.readthedocs.io/en/latest/library/asizeof.html 它说,

If all is True and if no positional arguments are supplied. size all current gc objects, including module, global and stack frame objects.

也许您正在寻找的是basicsize

from pympler import asizeof 
import gc
from keras.models import Sequential
from keras.layers import Dense

model_1 = Sequential([
  Dense(1, activation='relu', input_shape=(10,)),
])

gc.collect()
print('Model 1 size = ', asizeof.basicsize(model_1))

gc.collect()
model_2 = Sequential([
  Dense(1, activation='relu', input_shape=(10,)),
])

print('Model 1 size = ', asizeof.basicsize(model_1))

print('Model 2 size = ', asizeof.basicsize(model_2))

他们应该给同样的尺寸。