【问题标题】:How to avoid large memory consume custom loss function in keras如何避免大内存消耗keras中的自定义损失函数
【发布时间】:2020-08-21 13:15:34
【问题描述】:

我在 keras 中定义了一个自定义损失函数。在这个自定义损失函数中,我从y_pred 中提取非连续值,如下所示:

sel_row = tf.constant([[2],[5],[8]])
row_tmp = y_pred
selected = tf.transpose(tf.gather_nd(tf.transpose(row_tmp), sel_row))

有了这个,我只需从张量中选择列。现在,如果我对连续列(即row_tmp[:, 2:5])做同样的事情,我没有问题,但我得到的不是连续列:

/tensorflow/lib/python3.7/site-packages/tensorflow_core/python/framework/indexed_slices.py:424: 
UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. 
This may consume a large amount of memory.
  "Converting sparse IndexedSlices to a dense Tensor of unknown shape. "

一切正常,但最好有一个更好的方法来避免消耗太多内存。

我尝试将tf.constant 更改为tf.Variable,但出现此错误:

ValueError: tf.function-decorated function tried to create variables on non-first call.

有什么建议吗?

【问题讨论】:

    标签: python tensorflow keras backend loss-function


    【解决方案1】:

    你可以这样做:

    selected = tf.gather(row_tmp, tf.squeeze(sel_row, axis=1), axis=1)
    

    【讨论】:

    • 谢谢!它现在正在毫无警告地工作。但是您认为这种差异背后的原因是什么?我以为是tf.gather的错,但不是这样
    • @Cla 我不太确定,afaik 索引切片通常用于梯度计算,它是稀疏张量的“压缩”表示。我的感觉是tf.gather_nd 的梯度使用索引切片,tf.transpose 强制将其转换为密集张量,但我不能确定... Tbh 这是一个相对较低的实现细节,并且警告对于大多数用户来说,它本身可能并不太有用。
    猜你喜欢
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    • 2018-10-28
    • 2017-12-29
    • 2018-11-12
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多