【问题标题】:Memory Leak Keras TensorFlow1.8.0内存泄漏 Keras TensorFlow1.8.0
【发布时间】:2018-10-24 03:58:53
【问题描述】:

我需要帮助来最小化内存泄漏疑似代码。

我正在使用 Keras 最新的 tensorflow 1.8.0 和 python 3.6

当程序开始时,它逐渐增长到 giganytes..!!在这里需要帮助。

我正在使用 VGG16 网络对图像进行分类。我无法定位导致内存泄漏的问题。

是 tensorflow 的 bug 还是 python 受苦于这样的工作

代码是:

class_labels = ['cc','','cc','xx']

image = load_img(img_path, target_size=target_size)

image_arr = img_to_array(image) # convert from PIL Image to NumPy array
image_arr /= 255

image_arr = np.expand_dims(image_arr, axis=0)

model = applications.VGG16(include_top=False, weights='imagenet')  

bottleneck_features = model.predict(image_arr) 

model = create_top_model("softmax", bottleneck_features.shape[1:])

model.load_weights("res/_top_model_weights.h5")
numpy_horizontal_concat = cv2.imread(img_path)
xxx=1
path ="/home/dataset/test"
listOfFiles = os.listdir(path)
random.shuffle(listOfFiles)
pattern = "*.jpg"
model = applications.VGG16(include_top=False, weights='imagenet')

for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        image = load_img(path+"/"+ entry, target_size=target_size)
        start_time = time.time()

        image_arr = img_to_array(image)  # convert from PIL Image to NumPy array
        image_arr /= 255

        image_arr = np.expand_dims(image_arr, axis=0)

        bottleneck_features = model.predict(image_arr)

        model2 = create_top_model("softmax", bottleneck_features.shape[1:])

        model2.load_weights("res/_top_model_weights.h5")


        predicted = model2.predict(bottleneck_features)
        decoded_predictions = dict(zip(class_labels, predicted[0]))
        decoded_predictions = sorted(decoded_predictions.items(), key=operator.itemgetter(1), reverse=True)
        elapsed_time = time.time() - start_time

        print()
        count = 1
        for key, value in decoded_predictions[:5]:
            print("{}. {}: {:8f}%".format(count, key, value * 100))
            print("time:  " , time.strftime("%H:%M:%S", time.gmtime(elapsed_time)) , "  - " , elapsed_time)
            count += 1

        #OPENCV concat test
        #numpy_horizontal_concat = np.concatenate((mat_image,numpy_horizontal_concat), axis=0)

        hide_img = True
        model2=""
        predicted=""
        image_arr=""
        image=""

【问题讨论】:

  • 似乎有很多与 Keras 中奇怪的内存使用有关的问题。我收集了这篇文章的解决方法列表Keras memory leak

标签: python-3.x tensorflow memory-leaks keras deep-learning


【解决方案1】:

在您的 for 循环中,您可以构建一个带有加载权重的新模型。这个模型是在你的 tensorflow 会话中构建的,你不会重置它。因此,您的会话是由许多模型构建的,而不会删除一个模型。

有两种可能的解决方案:

  1. 尝试优化您只需加载一次模型的代码。这样您的代码也会变得更快
  2. 重置会话:

我强烈建议使用第一个解决方案,但如果这不可行:

from keras import backend as K
K.clear_session()

【讨论】:

  • 我更改了模型加载部分并添加了 k.clear_session() 它解决了内存泄漏问题。我认为对于边缘设备来说,最好的选择是 Caffe 和 Caffe2 对吗?
猜你喜欢
  • 2019-01-09
  • 1970-01-01
  • 2019-04-11
  • 2021-01-16
  • 1970-01-01
  • 2020-01-27
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多