问题描述
类似问题:
- K.ctc_decode() memory not released#6770
- K.ctc_decode() memory not released#9011
- Keras using Lambda layers error with K.ctc_decode
如下一段代码,在多次调用了K.ctc_decode时,会发现程序占用的内存会越来越高,执行速度越来越慢。
data = generator(...)
model = init_model(...)
for i in range(NUM):
x, y = next(data)
_y = model.predict(x)
shape = _y.shape
input_length = np.ones(shape[0]) * shape[1]
ctc_decode = K.ctc_decode(_y, input_length)[0][0]
out = K.get_value(ctc_decode)
原因
每次执行ctc_decode
时都会向计算图中添加一个节点,这样会导致计算图逐渐变大,从而影响计算速度和内存。
PS:有资料说是由于get_value
导致的,其中也给出了解决方案。
但是我将ctc_decode
放在循环体之外就不再出现内存和速度问题,这是否说明get_value
影响其实不大呢?
解决方案
- 通过
K.function
封装K.ctc_decode
,只需初始化一次,只向计算图中添加一个计算节点,然后多次调用该节点(函数)
data = generator(...)
model = init_model(...)
x = model.output # [batch_sizes, series_length, classes]
input_length = KL.Input(batch_shape=[None], dtype='int32')
ctc_decode = K.ctc_decode(x, input_length=input_length * K.shape(x)[1])
decode = K.function([model.input, input_length], [ctc_decode[0][0]])
for i in range(NUM):
_x, _y = next(data)
out = decode([_x, np.ones(1)])