如何减少内存使用量?

时间:2019-03-25 15:28:29

标签: python tensorflow

这是我的代码示例

def normalize_3D(input):
    for i in range(input.shape[0]):
        s = tf.concat([tf.reshape(input[i, 9, 0], shape=[1, 1]),
                       tf.reshape(input[i, 9, 1], shape=[1, 1]),
                       tf.reshape(input[i, 9, 2], shape=[1, 1])], axis=1)

        output = input[i, :, :] - s
        output2 = output / tf.sqrt(tf.square(input[i, 9, 0] - input[i, 0, 0]) +
                                   tf.square(input[i, 9, 1] - input[i, 0, 1]) +
                                   tf.square(input[i, 9, 2] - input[i, 0, 2]))
        output2 = tf.reshape(output2, [1, input.shape[1], input.shape[2]])
        if i == 0:
            output3 = output2
        else:
            output3 = tf.concat([output3, output2], axis=0)

    return output3

像该示例一样,我多次使用“ for”状态来计算仅有几批的数据。 但是,在编写代码时,我注意到它占用了大量内存,并且出现错误消息。 我的一些预测只是显示“ nan”,之后程序被卡住了。

计算批处理数据时,有什么方法可以减少这种内存滥用?

1 个答案:

答案 0 :(得分:0)

您的函数可以这样简单,高效地表达:

import tensorflow as tf

def normalize_3D(input):
    shift = input[:, 9]
    scale = tf.norm(input[:, 9] - input[:, 0], axis=1, keepdims=True)
    output = (input - tf.expand_dims(shift, 1)) / tf.expand_dims(scale, 1)
    return output
相关问题