pytorch 总结代码块笔记

1. 将张量( tensor )可视化

在CV的模型中,常常需要将某一个特征图可视化以进行调试或者其他操作。
使用matplotlib的画图工具,其中需要调用.detach()来将tensor抽离出来,因为后面还需要用numpy将tensor转成另外一种数据结构,如果不那么做,会报Can’t call numpy() on Variable that requires grad 的错误。具体可以参照[.data和.detach区别]。(https://blog.csdn.net/DreamHome_S/article/details/85259533)

 import matplotlib.pyplot as imsave

#要输出的tensor
output = torch.randn(batch_size,channel,img_high,img_width)
#因为是tensor,需要将它从GPU拿出来
out = output.data.cpu().numpy()
output_root ="../"
im_name=‘’123.png‘
if not os.path.exists(output_root):
	os.makedirs(output_root)
#根据batch_size打印,一般打印gary只需要两个维度的信息,而且只需要out后面两维
for i in range(batch_size)
	imsave(os.path.join(output_root,im_name),out[i][0],"gray")

pytorch 总结代码块笔记_第1张图片

你可能感兴趣的:(实用代码笔记)