You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu环境下model.predict()内存无法释放问题求助

内存泄漏问题修复方案

针对你遇到的model.predict()循环内存递增问题,核心原因是循环内错误调用clear_session()破坏了模型实例,导致TensorFlow每次预测都重复构建计算图,产生大量未释放的计算节点,同时Teachable Machine导出的模型在重复预测时存在临时张量未及时回收的情况。以下是具体修复方案:

方案1:调整会话清理逻辑,避免破坏模型实例

将clear_session()移至循环前后(仅初始化和结束时清理),循环内手动回收临时变量,同时改用TensorFlow张量替代numpy数组优化内存管理:

import keras
import cv2
import numpy as np
import tensorflow as tf

np.set_printoptions(suppress=True)

# 初始化前清理会话,避免残留计算图
keras.backend.clear_session()
model = keras.models.load_model('ml_files/model_lid.h5', compile=False)

camera = cv2.VideoCapture(2)

while True:
    ret, image = camera.read()
    if not ret:
        break  # 防止摄像头读取失败导致异常

    image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
    cv2.imshow("Webcam Image", image)

    # 转换为TensorFlow张量,减少numpy与TF之间的内存拷贝开销
    image_tensor = tf.convert_to_tensor(image, dtype=tf.float32)
    image_tensor = tf.reshape(image_tensor, (1, 224, 224, 3))
    image_tensor = (image_tensor / 127.5) - 1

    # 执行预测并立即释放结果内存,verbose=0关闭日志输出减少额外开销
    predictions = model.predict(image_tensor, verbose=0)
    del predictions

    keyboard_input = cv2.waitKey(1)
    if keyboard_input == 27:
        break

    # 手动回收当前循环的临时变量
    del image, image_tensor

camera.release()
cv2.destroyAllWindows()
# 程序结束前清理会话
keras.backend.clear_session()

方案2:用tf.function包装预测逻辑,避免重复构建计算图

tf.function会将预测逻辑编译为静态计算图,避免每次预测都重新追踪计算节点,大幅减少内存占用:

import keras
import cv2
import numpy as np
import tensorflow as tf

np.set_printoptions(suppress=True)

keras.backend.clear_session()
model = keras.models.load_model('ml_files/model_lid.h5', compile=False)

# 用tf.function包装预测函数,仅编译一次计算图
@tf.function
def predict_image(input_tensor):
    return model(input_tensor, training=False)  # 直接调用模型等价于predict,效率更高

camera = cv2.VideoCapture(2)

while True:
    ret, image = camera.read()
    if not ret:
        break

    image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
    cv2.imshow("Webcam Image", image)

    image_tensor = tf.convert_to_tensor(image, dtype=tf.float32)
    image_tensor = tf.reshape(image_tensor, (1, 224, 224, 3))
    image_tensor = (image_tensor / 127.5) - 1

    predictions = predict_image(image_tensor)
    del predictions

    keyboard_input = cv2.waitKey(1)
    if keyboard_input == 27:
        break

    del image, image_tensor

camera.release()
cv2.destroyAllWindows()
keras.backend.clear_session()

方案3:GPU环境下限制内存增长(可选)

如果使用GPU运行,TensorFlow默认会占用全部显存,可能导致内存泄漏的错觉,可添加内存按需分配逻辑:
在加载模型前插入以下代码:

gpus = tf.config.list_physical_devices('GPU')
if gpus:
    try:
        # 允许GPU内存按需分配,避免一次性占用全部显存
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)
    except RuntimeError as e:
        print(e)

额外注意事项

  • 确保TensorFlow/Keras版本为稳定版(如2.10.x或2.11.x),新版本可能修复了内存泄漏的底层bug;
  • 可安装psutil库实时监控内存:pip install psutil,循环内添加print(psutil.Process().memory_info().rss / 1024 ** 2)查看当前内存占用(单位:MB);
  • Teachable Machine导出的模型已包含预处理逻辑,避免在循环内重复创建预处理流程。

内容的提问来源于stack exchange,提问作者Przemysław

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:10:44