您好,登錄后才能下訂單哦!
這篇文章主要介紹了pytorch輸出中間層特征的示例分析,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
pytorch 輸出中間層特征:
tensorflow輸出中間特征,2種方式:
1. 保存全部模型(包括結(jié)構(gòu))時(shí),需要之前先add_to_collection 或者 用slim模塊下的end_points
2. 只保存模型參數(shù)時(shí),可以讀取網(wǎng)絡(luò)結(jié)構(gòu),然后按照對(duì)應(yīng)的中間層輸出即可。
but:Pytorch 論壇給出的答案并不好用,無論是hooks,還是重建網(wǎng)絡(luò)并去掉某些層,這些方法都不好用(在我看來)。
我們可以在創(chuàng)建網(wǎng)絡(luò)class時(shí),在forward時(shí)加入一個(gè)dict 或者 list,dict是將中間層名字與中間層輸出分別作為key:value,然后作為第二個(gè)值返回。前提是:運(yùn)行創(chuàng)建自己的網(wǎng)絡(luò)(無論fine-tune),只保存網(wǎng)絡(luò)參數(shù)。
個(gè)人理解:雖然每次運(yùn)行都返回2個(gè)值,但是運(yùn)行效率基本沒有變化。
附上代碼例子:
import torch import torchvision import numpy as np from torch import nn from torch.nn import init from torch.autograd import Variable from torch.utils import data EPOCH=20 BATCH_SIZE=64 LR=1e-2 train_data=torchvision.datasets.MNIST(root='./mnist',train=True, transform=torchvision.transforms.ToTensor(),download=False) train_loader=data.DataLoader(train_data,batch_size=BATCH_SIZE,shuffle=True) test_data=torchvision.datasets.MNIST(root='./mnist',train=False) test_x=Variable(torch.unsqueeze(test_data.test_data,dim=1).type(torch.FloatTensor)).cuda()/255 test_y=test_data.test_labels.cuda() class CNN(nn.Module): def __init__(self): super().__init__() self.conv1=nn.Sequential( nn.Conv2d(in_channels=1,out_channels=16,kernel_size=4,stride=1,padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=2,stride=2)) self.conv2=nn.Sequential(nn.Conv2d(16,32,4,1,2),nn.ReLU(),nn.MaxPool2d(2,2)) self.out=nn.Linear(32*7*7,10) def forward(self,x): per_out=[] ############修改處############## x=self.conv1(x) per_out.append(x) # conv1 x=self.conv2(x) per_out.append(x) # conv2 x=x.view(x.size(0),-1) output=self.out(x) return output,per_out cnn=CNN().cuda() # or cnn.cuda() optimizer=torch.optim.Adam(cnn.parameters(),lr=LR) loss_func=nn.CrossEntropyLoss().cuda()############################ for epoch in range(EPOCH): for step,(x,y) in enumerate(train_loader): b_x=Variable(x).cuda()# if channel==1 auto add c=1 b_y=Variable(y).cuda() # print(b_x.data.shape) optimizer.zero_grad() output=cnn(b_x)[0] ##原先只需要cnn(b_x) 但是現(xiàn)在需要用到第一個(gè)返回值## loss=loss_func(output,b_y)# Variable need to get .data loss.backward() optimizer.step() if step%50==0: test_output=cnn(test_x)[0] pred_y=torch.max(test_output,1)[1].cuda().data.squeeze() ''' why data ,because Variable .data to Tensor;and cuda() not to numpy() ,must to cpu and to numpy and .float compute decimal ''' accuracy=torch.sum(pred_y==test_y).data.float()/test_y.size(0) print('EPOCH: ',epoch,'| train_loss:%.4f'%loss.data[0],'| test accuracy:%.2f'%accuracy) # loss.data.cpu().numpy().item() get one value torch.save(cnn.state_dict(),'./model/model.pth') ##輸出中間層特征,根據(jù)索引調(diào)用## conv1: conv1=cnn(b_x)[1][0] conv2: conv2=cnn(b_x)[1][1]
##########################
hook使用:
res=torchvision.models.resnet18() def get_features_hook(self, input, output):# self 代表類模塊本身 print(output.data.cpu().numpy().shape) handle=res.layer2.register_forward_hook(get_features_hook) a=torch.ones([1,3,224,224])
b=res(a) 直接打印出 layer2的輸出形狀,但是不好用。因?yàn)?,?shí)際中,我們需要return,而hook明確指出 不可以return 只能print。
所以,不建議使用hook。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“pytorch輸出中間層特征的示例分析”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。