Tensoflow sess.run导致的内存溢出

       下面是调用模型进行批量测试的代码(出现溢出),开始以为导致溢出的原因是数据读入方式问题引起的,用了tf , PIL和cv等方式读入图片数据,发现越来越慢,内存占用飙升,调试时发现是sess.run这里出了问题(随着for循环进行速度越来越慢)。

    # Creates graph from saved GraphDef
    create_graph(pb_path)

    # Init tf Session
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    init = tf.global_variables_initializer()
    sess.run(init)


    input_image_tensor = sess.graph.get_tensor_by_name("create_inputs/batch:0") 
    output_tensor_name = sess.graph.get_tensor_by_name("conv6/out_1:0")  


    for filename in os.listdir(image_dir):
        image_path = os.path.join(image_dir, filename)
  
        start = time.time()
        image_data = cv2.imread(image_path)
        image_data = cv2.resize(image_data, (w, h))
        image_data_1 = image_data - IMG_MEAN
        input_image = np.expand_dims(image_data_1, 0)

        raw_output_up = tf.image.resize_bilinear(output_tensor_name, size=[h, w], align_corners=True) 
        raw_output_up = tf.argmax(raw_output_up, axis=3)
        

        predict_img = sess.run(raw_output_up, feed_dict={input_image_tensor: input_image})       # 1,height,width
        predict_img = np.squeeze(predict_img)     #  height, width 

        voc_palette = visual.make_palette(3)
        masked_im = visual.vis_seg(image_data, predict_img, voc_palette)
        cv2.imwrite("%s_pred.png" % (save_dir + filename.split(".")[0]), masked_im)


        print(time.time() - start)

    print(">>>>>>Done")

下面是解决溢出问题的代码(将部分代码放在for循环外

    # Creates graph from saved GraphDef
    create_graph(pb_path)

    # Init tf Session
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    init = tf.global_variables_initializer()
    sess.run(init)

    input_image_tensor = sess.graph.get_tensor_by_name("create_inputs/batch:0") 
    output_tensor_name = sess.graph.get_tensor_by_name("conv6/out_1:0")  
    
##############################################################################################################
    raw_output_up = tf.image.resize_bilinear(output_tensor_name, size=[h, w], align_corners=True) 
    raw_output_up = tf.argmax(raw_output_up, axis=3)
##############################################################################################################

    for filename in os.listdir(image_dir):
        image_path = os.path.join(image_dir, filename)
  
        start = time.time()
        image_data = cv2.imread(image_path)
        image_data = cv2.resize(image_data, (w, h))
        image_data_1 = image_data - IMG_MEAN
        input_image = np.expand_dims(image_data_1, 0)
        
        predict_img = sess.run(raw_output_up, feed_dict={input_image_tensor: input_image})       # 1,height,width
        predict_img = np.squeeze(predict_img)     #  height, width 

        voc_palette = visual.make_palette(3)
        masked_im = visual.vis_seg(image_data, predict_img, voc_palette)
        cv2.imwrite("%s_pred.png" % (save_dir + filename.split(".")[0]), masked_im)
        print(time.time() - start)

    print(">>>>>>Done")

 总结:

  1. 在迭代过程中, 在sess.run的for循环中不要加入tensorflow一些op操作,会增加图节点,否则随着迭代的进行,tf的图会越来越大,最终导致溢出;
  2. 建议不要使用tf.gfile.FastGFile(image_path, 'rb').read()读入数据(有可能会造成溢出),用opencv之类读取。
### TensorFlow Argmax 函数返回不正确结果的解决方案 当遇到 `tf.argmax` 返回的结果不符合预期时,可能的原因有很多。一种常见的情况是在处理数值稳定性问题时出现了溢出或下溢现象。 #### 数值稳定性的考虑 在计算诸如softmax这样的操作时,如果输入logits中的数值过大或过小,则可能导致浮点数运算不稳定,进而影响后续依赖于这些值的操作,比如 `argmax` 的准确性[^1]。 为了防止这种情况发生,在实现自定义函数(如上面提到的unstable softmax)时应该加入数值稳定的措施: ```python import tensorflow as tf def stable_softmax(logits): # Subtract max value from logits for numerical stability shifted_logits = logits - tf.reduce_max(logits) exp_shifted = tf.exp(shifted_logits) return exp_shifted / tf.reduce_sum(exp_shifted) # Example usage with session run (for TF 1.x style code) with tf.compat.v1.Session() as sess: print(sess.run(stable_softmax([1000., 0.]))) # Should now work correctly without NaNs ``` 对于更现代版本的TensorFlow(2.x),可以直接利用内置的支持自动求导和其他特性的API来进行类似的修正,并且不需要显式的会话管理: ```python import tensorflow as tf @tf.function def get_argmax_stably(input_tensor): # Ensure input tensor is float type to avoid precision issues float_input = tf.cast(input_tensor, dtype=tf.float32) # Apply stabilization trick before applying softmax stabilized_values = float_input - tf.math.reduce_max(float_input) probabilities = tf.nn.softmax(stabilized_values) # Get index of maximum probability which corresponds to original argmax predicted_class_index = tf.math.argmax(probabilities).numpy() return predicted_class_index input_data = [1000., 0.] print(get_argmax_stably(tf.constant(input_data))) ``` 通过上述方法可以有效提高 `argmax` 结果的可靠性,尤其是在面对极端数值的情况下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值