Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tensorflow在计算时内存不足:如何查找内存泄漏?_Python_Tensorflow_Memory Leaks_Out Of Memory - Fatal编程技术网

Python Tensorflow在计算时内存不足:如何查找内存泄漏?

Python Tensorflow在计算时内存不足:如何查找内存泄漏?,python,tensorflow,memory-leaks,out-of-memory,Python,Tensorflow,Memory Leaks,Out Of Memory,我正在使用谷歌的TensorFlow DeepDream实现()在一个目录中迭代地做深度梦 我的代码如下: model_fn = tensorflow_inception_graph.pb # creating TensorFlow session and loading the model graph = tf.Graph() sess = tf.InteractiveSession(graph=graph) with tf.gfile.FastGFile(model_fn, 'rb') a

我正在使用谷歌的TensorFlow DeepDream实现()在一个目录中迭代地做深度梦

我的代码如下:

model_fn = tensorflow_inception_graph.pb

# creating TensorFlow session and loading the model
graph = tf.Graph()
sess = tf.InteractiveSession(graph=graph)
with tf.gfile.FastGFile(model_fn, 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
t_input = tf.placeholder(np.float32, name='input') # define the input tensor
imagenet_mean = 117.0
t_preprocessed = tf.expand_dims(t_input-imagenet_mean, 0)
tf.import_graph_def(graph_def, {'input':t_preprocessed})



def render_deepdream(t_obj, img0=img_noise,
                     iter_n=10, step=1.5, octave_n=4, octave_scale=1.4):
    t_score = tf.reduce_mean(t_obj) # defining the optimization objective
    t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!

    # split the image into a number of octaves
    img = img0
    octaves = []
    for i in range(octave_n-1):
        hw = img.shape[:2]
        lo = resize(img, np.int32(np.float32(hw)/octave_scale))
        hi = img-resize(lo, hw)
        img = lo
        octaves.append(hi)

    # generate details octave by octave
    for octave in range(octave_n):
        if octave>0:
            hi = octaves[-octave]
            img = resize(img, hi.shape[:2])+hi
        for i in range(iter_n):
            g = calc_grad_tiled(img, t_grad)
            img += g*(step / (np.abs(g).mean()+1e-7))
            #print('.',end = ' ')
        #clear_output()
    #showarray(img/255.0)
    return img/255.0


def morphPicture(filename1,filename2,blend,width):
    img1 = PIL.Image.open(filename1)
    img2 = PIL.Image.open(filename2)
    if width is not 0:
        img2 = resizePicture(filename2,width)
    finalImage= PIL.Image.blend(img1, img2, blend)
    del img1
    del img2
    return finalImage

def save_array(arr, name,direc, ext="png"):
    img = np.uint8(np.clip(arr, 0, 1)*255)
    img =cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    cv2.imwrite("{d}/{n}.{e}".format(d=direc, n=name, e=ext), img)
    del img

framesDir = "my directory"
os.chdir(framesDir)

outputDir ="my directory"
for file in os.listdir(framesDir):
    img0 = PIL.Image.open(file)
    img0 = np.float32(img0)
    dreamedImage = render_deepdream(tf.square(T('mixed4c')),img0,iter_n=3,octave_n=6)
    save_array(dreamedImage,1,outputDir,'jpg')
    break

i=1
j=0
with tf.device('/gpu:0'):
    for file in os.listdir(framesDir):
        if j<=1: #already processed first image so we skip it here
            j+=1
            continue
        else:
            dreamedImage = "my directory"+str(i)+'.jpg' # get the previous deep dreamed frame

            img1 = file # get the next undreamed frame

            morphedImage = morphPicture(dreamedImage,img1,0.5,0) #blend the images
            morphedImage=np.float32(morphedImage)
            dreamedImage = render_deepdream(tf.square(T('mixed4c')),morphedImage,iter_n=3,octave_n=6) #deep dream a 
                                                                                                    #blend of the two frames
            i+=1
            save_array(dreamedImage,i,outputDir,'jpg') #save the dreamed image
            del dreamedImage
            del img1
            del morphedImage


            time.sleep(0.5)
model\u fn=tensorflow\u inception\u graph.pb
#创建TensorFlow会话并加载模型
graph=tf.graph()
sess=tf.InteractiveSession(graph=graph)
将tf.gfile.FastGFile(model_fn,'rb')作为f:
graph_def=tf.GraphDef()
graph_def.ParseFromString(f.read())
t_input=tf.placeholder(np.float32,name='input')#定义输入张量
imagenet_平均值=117.0
t_preprocessed=tf.expand_dims(t_input-imagenet_平均值,0)
tf.import_graph_def(graph_def,{'input':t_preprocessed})
def render_deepdream(t_obj,img0=img_噪声,
iter n=10,阶跃=1.5,倍频程=4,倍频程=1.4):
t_得分=tf.减少平均值(t_obj)#定义优化目标
t_grad=tf.梯度(t_分数,t_输入)[0]#看看自动微分的力量吧!
#将图像分割为若干个八度音阶
img=img0
倍频程=[]
对于范围内的i(倍频程n-1):
hw=图像形状[:2]
lo=调整大小(img,np.int32(np.float32(hw)/倍频程)
hi=img调整大小(lo,hw)
img=lo
八度音阶。附加(hi)
#按倍频程生成详细信息
对于范围内的倍频程(倍频程n):
如果倍频程>0:
hi=倍频程[-倍频程]
img=调整大小(img,hi.shape[:2])+hi
对于范围内的i(iter\n):
g=计算梯度(img,t梯度)
img+=g*(步长/(np.abs(g.mean()+1e-7))
#打印('.',结束='')
#清除输出()
#showarray(img/255.0)
返回img/255.0
def变形图片(文件名1、文件名2、混合、宽度):
img1=PIL.Image.open(filename1)
img2=PIL.Image.open(filename2)
如果宽度不是0:
img2=调整图片大小(文件名2,宽度)
finalImage=PIL.Image.blend(img1、img2、blend)
del img1
del img2
返回最终授权
def save_数组(arr,name,direc,ext=“png”):
img=np.uint8(np.clip(arr,0,1)*255)
img=cv2.cvt颜色(img,cv2.COLOR_RGB2BGR)
imwrite(“{d}/{n}.{e}.”格式(d=direc,n=name,e=ext),img)
德莱姆
framesDir=“我的目录”
os.chdir(framesDir)
outputDir=“我的目录”
对于os.listdir(framesDir)中的文件:
img0=PIL.Image.open(文件)
img0=np.float32(img0)
dreamedImage=render_deepdream(tf.square(T('mixed4c')),img0,iter_n=3,倍频程_n=6)
save_数组(dreamedImage,1,outputDir,'jpg')
打破
i=1
j=0
使用tf.device('/gpu:0'):
对于os.listdir(framesDir)中的文件:

如果j99%,当使用tensorflow时,“内存泄漏”实际上是由于在迭代过程中不断添加到图形中的操作造成的,而不是先构建图形,然后在循环中使用它

使用tf.device('/gpu:0
)为循环指定设备(
)的事实表明情况确实如此:通常为新节点指定设备,因为这不会影响已定义的节点

幸运的是,tensorflow有一个方便的工具来发现这些错误:。调用此函数时,将阻止进一步的节点添加到图形中。最好在迭代之前调用此函数


因此,在您的情况下,我会在循环之前调用
tf.get\u default\u graph().finalize()
,查找它可能引发的任何错误。

99%的时间,在使用tensorflow时,“内存泄漏”实际上是由于在迭代过程中不断添加到图中的操作,而不是先构建图,然后在循环中使用它

使用tf.device('/gpu:0
)为循环指定设备(
)的事实表明情况确实如此:通常为新节点指定设备,因为这不会影响已定义的节点

幸运的是,tensorflow有一个方便的工具来发现这些错误:。调用此函数时,将阻止进一步的节点添加到图形中。最好在迭代之前调用此函数


因此,在您的情况下,我将调用
tf.get\u default\u graph().finalize()
在你的循环之前,寻找它可能抛出的任何错误。

你似乎是正确的,因为我现在得到了一个
运行时错误:图形已完成,无法修改
。那么,我如何首先构建一个合适的图形?我已经用当前用于构建图形的代码更新了我的问题。对不起,我对TensorFlow非常陌生。`你呢似乎是正确的,因为我现在得到了一个
运行时错误:图形已定稿,无法修改
。然后如何先构建一个合适的图形?我已经用当前用于构建图形的代码更新了我的问题。抱歉,我对TensorFlow非常陌生`