引发RuntimeError(“发电机没有停止”)RuntimeError:发电机没有停止

时间:2019-12-18 01:25:25

标签: python memory error-handling contextmanager

它产生带有

的消息
  

提高RuntimeError(“发电机没有停止”)RuntimeError:发电机   没有停止

Tryint使用上下文管理是因为要释放内存时
genereate_image完成称为

在我的内存保持上升的过程中,我必须运行generate_image 500000次
如果您有更好的解决方案,请告诉我

 @contextmanager
    def generate_image(self, img, i):
        #print("=================generate image=============================")
        img = Variable(img, requires_grad=True)

        #image_PIL = transforms.ToPILImage()(img[0])
        #image_PIL.save('result/test{}.jpg'.format(i))

        self.net._modules.get(self.finalconv_name).register_forward_hook(self.hook_feature)

        img_tensor = img.to(self.device)
        logit , _ = self.net(img_tensor)
        h_x = F.softmax(logit, dim=1).data.squeeze()

        weight_softmaxtemp = self.weight_softmax
        feature_blobstemp = self.feature_blobs[0]
        probs, idx = h_x.sort(0, True)
        idx_temp = [idx[0]]
        output_cam = self.returnCAM(self.feature_blobs[0],self.weight_softmax,[idx[0].item()])
        height, width = 28,28
        heatmap = cv2.applyColorMap(cv2.resize(output_cam[0], (width, height)), cv2.COLORMAP_JET)
        heatmap2 = cv2.resize(output_cam[0],(width,height))


        img =img.detach().numpy()
        img2 = img[0]
        img2 = np.transpose(img2,axes=(1,2,0))
        img2=cv2.resize(img2,(28,28))

        #TODO erase
        img2 = cv2.applyColorMap(cv2.resize(output_cam[0], (width, height)), cv2.COLORMAP_JET)


        camsresult = np.array(list(map(resize_image, heatmap, img2)))
        del img_tensor,output_cam,heatmap2,img2,img
        gc.collect()
        result = zip(camsresult, heatmap, probs.detach().cpu().numpy(), idx.detach().cpu().numpy())
        return result


with self.generate_image(img,idx) as result:
     sal_maps_b, heat_map_b, probs_b, preds_b = result

0 个答案:

没有答案