python - 使用 mplfinance/matplotlib 时可能出现内存泄漏。如何解决?

标签 python python-3.x matplotlib anaconda mplfinance

我正在尝试为 CNN 制作大量(约 170 万张)图像(带体积的烛台图)。但是,我目前拥有的脚本在每次迭代后不断增加其内存使用量,据我所知,每次迭代大约 2-5mb。无论我正在运行多少个脚本实例,这都会增加直到我的内存完全填满。 (其中脚本最终使用 11-12 GB 的 16GB)。
目标是同时运行脚本的多个实例。我尝试了并行处理,结果不是很好。因此,我只是使用多个内核。我尝试了很多方法来减少内存使用,但似乎没有任何效果。
我在 VS 代码中使用 Jupyter 笔记本(Python 3.8.5)(anaconda),具有 64 位 Windows 系统。 16GB 内存和英特尔 i7 第 8 代。
第一个单元调用包,加载数据并设置参数。

# import required packages 
import matplotlib.dates as mpdates 
import matplotlib.pyplot as plt 
import mplfinance as mpf
import matplotlib as mpl
from PIL import Image
import pandas as pd 
import math as math
import numpy as np
import io   as io
import gc   as gc
import os as os


#set run instance number
run=1

#timeframe
tf = 20

#set_pixels
img_size=56

#colors
col_up = '#00FF00'
col_down = '#FF0000'
col_vol = "#0000FF"

#set directory
direct = "C:/Users/robin/1 - Scriptie/images/"

#loading the data
data1 = pd.read_csv(r'D:\1 - School\Econometrics\2020 - 2021\Scriptie\Explainable AI\Scripts\Data\test_data.csv',header=[0, 1] , index_col = 0 )
data1.index=pd.to_datetime(data1.index)

#subsetting the data
total_symbols = math.floor(len(data1.columns.unique(level=0))/6)
symbols1 = data1.columns.unique(level=0)[(run-1)*total_symbols:run*total_symbols]

#set the plot parameters
mc = mpf.make_marketcolors(up = col_up ,down = col_down, edge='inherit', volume= col_vol, wick='inherit')
s  = mpf.make_mpf_style(marketcolors=mc)   

第二个单元格定义用于绘制图表的函数:
# creating candlestick chart with volume
def plot_candle(i,j,data,symbols,s,mc,direct,img_size, tf):
     
    #slicing data into 30 trading day windows
    data_temp=data[symbols[j]][i-tf:i]  

    #creating and saving the candlestick charts
    buf = io.BytesIO()
    save = dict(fname= buf, rc = (["boxplot.whiskerprops.linewidth",10]), 
                    pad_inches=0,bbox_inches='tight')
    mpf.plot(data_temp,savefig=save, type='candle',style=s, volume=True, axisoff=True,figratio=(1,1),closefig=True)
    buf.seek(0)
    im = Image.open(buf).resize((img_size,img_size))
    im.save(direct+"/"+str(symbols[j])+"/"+str(i-tf+1)+".png", "PNG")
    buf.close()
    plt.close("all")
第三个单元格遍历数据并调用第二个单元格中的函数。
#check if images folder excists, if not, create it. 
if not os.path.exists(direct):
    os.mkdir("C:/Users/robin/1 - Scriptie/images")

for j in range(0,len(symbols1)):

    #Check if symbol folder excists, if not, create it 
    if not os.path.exists(direct+"/"+symbols1[j]):
             os.mkdir(direct + "/"+symbols1[j])

    for i in range(tf,len(data1)) :

        #check if the file has already been created
        if not os.path.exists(direct+"/"+str(symbols1[j])+"/"   +str(i-tf+1)+".png"):
            #call the functions and create the 
            plot_candle(i , j , data1 , symbols1 ,s ,mc ,direct , img_size, tf)
            gc.collect()

最佳答案

从评论中推广:
问题是默认情况下 Matplotlib 尝试使用基于 GUI 的后端(它为每个绘图创建一个 GUI 窗口)。当您关闭它们时,我们会拆除我们的一面,并告诉 GUI 拆除其(基于 C++)的一面。然而,这种拆卸发生在 GUI 事件循环上,在这种情况下它永远不会运行,因此 c++ 端对象在“即将被删除”状态中积累,直到它耗尽内存。
通过将后端设置为 'agg'我们根本不尝试制作任何 GUI 窗口,因此没有要拆除的 GUI 对象(最好的优化是不做这件事 ;))。我希望它在墙上时间也稍微快一点(因为再次,不要做你不需要做的工作!)。
https://matplotlib.org/tutorials/introductory/usage.html#backends有关后端的更多详细信息,请参阅 https://matplotlib.org/users/interactive.html以及有关 GUI 集成如何工作的链接。

关于python - 使用 mplfinance/matplotlib 时可能出现内存泄漏。如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65058442/

相关文章:

python - pyparsing 值列表的递归 (ibm Rhapsody)

python - Pandas /pyplot 散点图 : set axis labels not working

Python从不同文件导入不同结果

python - 如何在Python中修改def的行为?

python - 从文本文件中读取特定的 Python 列表

python-3.x - 如何删除opencv上的鼠标滚轮默认缩放

python - django-admin startproject 不能在 OS X 上使用 python3

python - 如何使用 matplotlib 绘制多元线性回归模型

python-3.x - 绘图时的 Matplotlib 索引错误

python - 如何找到运动物体轨迹中的冗余路径(子路径)?