使用pytorch实现可视化中间层的结果
摘要
一直比较想知道图片经过卷积之后中间层的结果,于是使用pytorch写了一个脚本查看,先看效果
这是原图,随便从网上下载的一张大概224*224大小的图片,如下
网络介绍
我们使用的VGG16,包含RULE层总共有30层可以可视化的结果,我们把这30层分别保存在30个文件夹中,每个文件中根据特征的大小保存了64~128张图片
结果如下:
原图大小为224224,经过第一层后大小为64224*224,下面是第一层可视化的结果,总共有64张这样的图片:
下面看看第六层的结果
这层的输出大小是1128112*112,总共有128张这样的图片
下面是完整的代码
importcv2
importnumpyasnp
importtorch
fromtorch.autogradimportVariable
fromtorchvisionimportmodels
#创建30个文件夹
defmkdir(path):#判断是否存在指定文件夹,不存在则创建
#引入模块
importos
#去除首位空格
path=path.strip()
#去除尾部\符号
path=path.rstrip("\\")
#判断路径是否存在
#存在True
#不存在False
isExists=os.path.exists(path)
#判断结果
ifnotisExists:
#如果不存在则创建目录
#创建目录操作函数
os.makedirs(path)
returnTrue
else:
returnFalse
defpreprocess_image(cv2im,resize_im=True):
"""
ProcessesimageforCNNs
Args:
PIL_img(PIL_img):Imagetoprocess
resize_im(bool):Resizeto224ornot
returns:
im_as_var(Pytorchvariable):Variablethatcontainsprocessedfloattensor
"""
#meanandstdlistforchannels(Imagenet)
mean=[0.485,0.456,0.406]
std=[0.229,0.224,0.225]
#Resizeimage
ifresize_im:
cv2im=cv2.resize(cv2im,(224,224))
im_as_arr=np.float32(cv2im)
im_as_arr=np.ascontiguousarray(im_as_arr[...,::-1])
im_as_arr=im_as_arr.transpose(2,0,1)#ConvertarraytoD,W,H
#Normalizethechannels
forchannel,_inenumerate(im_as_arr):
im_as_arr[channel]/=255
im_as_arr[channel]-=mean[channel]
im_as_arr[channel]/=std[channel]
#Converttofloattensor
im_as_ten=torch.from_numpy(im_as_arr).float()
#Addonemorechanneltothebeginning.Tensorshape=1,3,224,224
im_as_ten.unsqueeze_(0)
#ConverttoPytorchvariable
im_as_var=Variable(im_as_ten,requires_grad=True)
returnim_as_var
classFeatureVisualization():
def__init__(self,img_path,selected_layer):
self.img_path=img_path
self.selected_layer=selected_layer
self.pretrained_model=models.vgg16(pretrained=True).features
#print(self.pretrained_model)
defprocess_image(self):
img=cv2.imread(self.img_path)
img=preprocess_image(img)
returnimg
defget_feature(self):
#input=Variable(torch.randn(1,3,224,224))
input=self.process_image()
print("inputshape",input.shape)
x=input
forindex,layerinenumerate(self.pretrained_model):
#print(index)
#print(layer)
x=layer(x)
if(index==self.selected_layer):
returnx
defget_single_feature(self):
features=self.get_feature()
print("features.shape",features.shape)
feature=features[:,0,:,:]
print(feature.shape)
feature=feature.view(feature.shape[1],feature.shape[2])
print(feature.shape)
returnfeatures
defsave_feature_to_img(self):
#tonumpy
features=self.get_single_feature()
foriinrange(features.shape[1]):
feature=features[:,i,:,:]
feature=feature.view(feature.shape[1],feature.shape[2])
feature=feature.data.numpy()
#usesigmodto[0,1]
feature=1.0/(1+np.exp(-1*feature))
#to[0,255]
feature=np.round(feature*255)
print(feature[0])
mkdir('./feature/'+str(self.selected_layer))
cv2.imwrite('./feature/'+str(self.selected_layer)+'/'+str(i)+'.jpg',feature)
if__name__=='__main__':
#getclass
forkinrange(30):
myClass=FeatureVisualization('/home/lqy/examples/TRP.PNG',k)
print(myClass.pretrained_model)
myClass.save_feature_to_img()
以上这篇使用pytorch实现可视化中间层的结果就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。