最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決Keras中循環(huán)使用K.ctc_decode內(nèi)存不釋放的問題

 更新時間:2020年06月29日 09:38:18   作者:愛明_愛夏  
這篇文章主要介紹了解決Keras中循環(huán)使用K.ctc_decode內(nèi)存不釋放的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

如下一段代碼,在多次調(diào)用了K.ctc_decode時,會發(fā)現(xiàn)程序占用的內(nèi)存會越來越高,執(zhí)行速度越來越慢。

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)

原因

每次執(zhí)行ctc_decode時都會向計算圖中添加一個節(jié)點,這樣會導(dǎo)致計算圖逐漸變大,從而影響計算速度和內(nèi)存。

PS:有資料說是由于get_value導(dǎo)致的,其中也給出了解決方案。

但是我將ctc_decode放在循環(huán)體之外就不再出現(xiàn)內(nèi)存和速度問題,這是否說明get_value影響其實不大呢?

解決方案

通過K.function封裝K.ctc_decode,只需初始化一次,只向計算圖中添加一個計算節(jié)點,然后多次調(diào)用該節(jié)點(函數(shù))

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)])

補充知識:CTC_loss和CTC_decode的模型封裝代碼避免節(jié)點不斷增加

該問題可以參考上面的描述,無論是CTC_decode還是CTC_loss,每次運行都會創(chuàng)建節(jié)點,避免的方法是將其封裝到model中,這樣就固定了計算節(jié)點。

測試方法: 在初始化節(jié)點后(注意是在運行fit/predict至少一次后,因為這些方法也會更改計算圖狀態(tài)),運行K.get_session().graph.finalize()鎖定節(jié)點,此時如果圖節(jié)點變了會報錯并提示出錯代碼。

from keras import backend as K
from keras.layers import Lambda,Input
from keras import Model
from tensorflow.python.ops import ctc_ops as ctc
import tensorflow as tf
from keras.layers import Layer
class CTC_Batch_Cost():
  '''
  用于計算CTC loss
  '''
  def ctc_lambda_func(self,args):
    """Runs CTC loss algorithm on each batch element.

    # Arguments
      y_true: tensor `(samples, max_string_length)` 真實標簽
      y_pred: tensor `(samples, time_steps, num_categories)` 預(yù)測前未經(jīng)過softmax的向量
      input_length: tensor `(samples, 1)` 每一個y_pred的長度
      label_length: tensor `(samples, 1)` 每一個y_true的長度

      # Returns
        Tensor with shape (samples,1) 包含了每一個樣本的ctc loss
      """
    y_true, y_pred, input_length, label_length = args

    # y_pred = y_pred[:, :, :]
    # y_pred = y_pred[:, 2:, :]
    return self.ctc_batch_cost(y_true, y_pred, input_length, label_length)

  def __call__(self, args):
    '''
    ctc_decode 每次創(chuàng)建會生成一個節(jié)點,這里參考了上面的內(nèi)容
    將ctc封裝成模型,是否會解決這個問題還沒有測試過這種方法是否還會出現(xiàn)創(chuàng)建節(jié)點的問題
    '''
    y_true = Input(shape=(None,))
    y_pred = Input(shape=(None,None))
    input_length = Input(shape=(1,))
    label_length = Input(shape=(1,))

    lamd = Lambda(self.ctc_lambda_func, output_shape=(1,), name='ctc')([y_true,y_pred,input_length,label_length])
    model = Model([y_true,y_pred,input_length,label_length],[lamd],name="ctc")

    # return Lambda(self.ctc_lambda_func, output_shape=(1,), name='ctc')(args)
    return model(args)

  def ctc_batch_cost(self,y_true, y_pred, input_length, label_length):
    """Runs CTC loss algorithm on each batch element.

    # Arguments
      y_true: tensor `(samples, max_string_length)`
        containing the truth labels.
      y_pred: tensor `(samples, time_steps, num_categories)`
        containing the prediction, or output of the softmax.
      input_length: tensor `(samples, 1)` containing the sequence length for
        each batch item in `y_pred`.
      label_length: tensor `(samples, 1)` containing the sequence length for
        each batch item in `y_true`.

    # Returns
      Tensor with shape (samples,1) containing the
        CTC loss of each element.
    """
    label_length = tf.to_int32(tf.squeeze(label_length, axis=-1))
    input_length = tf.to_int32(tf.squeeze(input_length, axis=-1))
    sparse_labels = tf.to_int32(K.ctc_label_dense_to_sparse(y_true, label_length))

    y_pred = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + 1e-7)

    # 注意這里的True是為了忽略解碼失敗的情況,此時loss會變成nan直到下一個個batch
    return tf.expand_dims(ctc.ctc_loss(inputs=y_pred,
                      labels=sparse_labels,
                      sequence_length=input_length,
                      ignore_longer_outputs_than_inputs=True), 1)

# 使用方法:(注意shape)
loss_out = CTC_Batch_Cost()([y_true, y_pred, audio_length, label_length])
from keras import backend as K
from keras.layers import Lambda,Input
from keras import Model
from tensorflow.python.ops import ctc_ops as ctc
import tensorflow as tf
from keras.layers import Layer

class CTCDecodeLayer(Layer):

  def __init__(self, **kwargs):
    super().__init__(**kwargs)

  def _ctc_decode(self,args):
    base_pred, in_len = args
    in_len = K.squeeze(in_len,axis=-1)

    r = K.ctc_decode(base_pred, in_len, greedy=True, beam_width=100, top_paths=1)
    r1 = r[0][0]
    prob = r[1][0]
    return [r1,prob]

  def call(self, inputs, **kwargs):
    return self._ctc_decode(inputs)

  def compute_output_shape(self, input_shape):
    return [(None,None),(1,)]

class CTCDecode():
  '''用與CTC 解碼,得到真實語音序列
      2019年7月18日所寫,對ctc_decode使用模型進行了封裝,從而在初始化完成后不會再有新節(jié)點的產(chǎn)生
  '''
  def __init__(self):
    base_pred = Input(shape=[None,None],name="pred")
    feature_len = Input(shape=[1,],name="feature_len")
    r1, prob = CTCDecodeLayer()([base_pred,feature_len])
    self.model = Model([base_pred,feature_len],[r1,prob])
    pass

  def ctc_decode(self,base_pred,in_len,return_prob = False):
    '''
    :param base_pred:[sample,timestamp,vector]
    :param in_len: [sample,1]
    :return:
    '''
    result,prob = self.model.predict([base_pred,in_len])
    if return_prob:
      return result,prob
    return result

  def __call__(self,base_pred,in_len,return_prob = False):
    return self.ctc_decode(base_pred,in_len,return_prob)


# 使用方法:(注意shape,是batch級的輸入)
ctc_decoder = CTCDecode()
ctc_decoder.ctc_decode(result,feature_len) 

以上這篇解決Keras中循環(huán)使用K.ctc_decode內(nèi)存不釋放的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 用python畫個敬業(yè)福字代碼

    用python畫個敬業(yè)福字代碼

    大家好,本篇文章主要講的是用python畫個敬業(yè)福字代碼,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01
  • Python按條件批量刪除TXT文件行工具

    Python按條件批量刪除TXT文件行工具

    這篇文章主要為大家詳細介紹了Python如何實現(xiàn)按條件批量刪除TXT文件中行的工具,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-12-12
  • 如何使用 Python 中的功能和庫創(chuàng)建 n-gram的過程

    如何使用 Python 中的功能和庫創(chuàng)建 n-gram的過程

    在計算語言學中,n-gram 對于語言處理、上下文和語義分析非常重要,本文將討論如何使用 Python 中的功能和庫創(chuàng)建 n-gram,感興趣的朋友一起看看吧
    2023-09-09
  • Python+Plotly繪制精美的數(shù)據(jù)分析圖

    Python+Plotly繪制精美的數(shù)據(jù)分析圖

    Plotly?是目前已知的Python最強繪圖庫,比Echarts還強大許多。它的繪制通過生成一個web頁面完成,并且支持調(diào)整圖像大小,動態(tài)調(diào)節(jié)參數(shù)。本文將利用Plotly繪制精美的數(shù)據(jù)分析圖,感興趣的可以了解一下
    2022-05-05
  • numpy數(shù)組的重塑和轉(zhuǎn)置實現(xiàn)

    numpy數(shù)組的重塑和轉(zhuǎn)置實現(xiàn)

    本文主要介紹了numpy數(shù)組的重塑和轉(zhuǎn)置實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-03-03
  • 在Python中使用異步Socket編程性能測試

    在Python中使用異步Socket編程性能測試

    異步網(wǎng)絡(luò)據(jù)說能極大的提高網(wǎng)絡(luò)server的連接速度,所以打算寫一個專題,來學習和了解異步網(wǎng)絡(luò).因為Python有個非常出名的異步Lib:Twisted,所以就用Python來完成.
    2014-06-06
  • 利用Python庫Scapy解析pcap文件的方法

    利用Python庫Scapy解析pcap文件的方法

    今天小編就為大家分享一篇利用Python庫Scapy解析pcap文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python實現(xiàn)百度文庫自動化爬取

    python實現(xiàn)百度文庫自動化爬取

    項目是合法項目,只是進行數(shù)據(jù)解析而已,不能下載看不到的內(nèi)容.部分文檔在電腦端不能預(yù)覽,但是在手機端可以預(yù)覽,所有本項目把瀏覽器瀏覽格式改成手機端,支持Windows和Ubuntu. 本項目使用的是chromedriver來控制chrome來模擬人來操作來進行文檔爬取
    2021-04-04
  • Python?Pygame實戰(zhàn)之紅心大戰(zhàn)游戲的實現(xiàn)

    Python?Pygame實戰(zhàn)之紅心大戰(zhàn)游戲的實現(xiàn)

    說起Windows自帶的游戲,相信許多80、90后的朋友都不陌生。本文就將利用Python中的Pygame模塊實現(xiàn)一下windows經(jīng)典游戲之一的紅心大戰(zhàn),需要的可以參考一下
    2022-02-02
  • django模板加載靜態(tài)文件的方法步驟

    django模板加載靜態(tài)文件的方法步驟

    這篇文章主要介紹了django模板加載靜態(tài)文件的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-03-03

最新評論

五家渠市| 九江县| 祥云县| 漠河县| 肇州县| 东乡| 镶黄旗| 方正县| 翁牛特旗| 石泉县| 广水市| 乳源| 华坪县| 荆门市| 河津市| 奉节县| 庄河市| 惠东县| 左权县| 汤阴县| 扎囊县| 新余市| 钟山县| 盘锦市| 惠州市| 安康市| 融水| 岫岩| 永定县| 双桥区| 山丹县| 刚察县| 若羌县| 龙井市| 毕节市| 资中县| 辰溪县| 灵川县| 益阳市| 诏安县| 江山市|