找到了一個解決方案,把它留作下面這個問題的答案:)
關于該專案的資訊:具有 2 個類的分類任務。
我正在嘗試為我在運行時放入模型的每個影像獲取模型的完全連接層的輸出。我計劃在模型完成訓練或測驗所有影像以使用 UMAP 進行可視化后使用它們。
該模型:
#Load resnet
def get_model():
model = torchvision.models.resnet50(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2)
return model
pl模塊的相關部分:
class classifierModel(pl.LightningModule):
def __init__(self, model):
super().__init__()
self.model = model
self.learning_rate = 0.0001
def training_step(self, batch, batch_idx):
x= batch['image']
y = batch['targets']
x_hat = self.model(x)
output = nn.CrossEntropyLoss()
loss= output(x_hat,y)
return loss
def test_step(self, batch, batch_idx):
x= batch['image']
y = batch['targets']
x_hat = self.model(x)
是否可以通過向 pl 模塊的 init 添加一個空串列然后在x_hat = model(x)執行后添加輸出來做到這一點?我怎么知道x_hat = model(x)執行后是否不會立即洗掉/丟棄 out_features?
uj5u.com熱心網友回復:
x_hat是這個向量并且是[batch_size, 2048]。所以只需修改你的訓練步驟也回傳x_hat。
class classifierModel(pl.LightningModule):
def __init__(self, model):
super().__init__()
self.model = model
self.learning_rate = 0.0001
self.fc_outputs = []
def training_step(self, batch, batch_idx):
x= batch['image']
y = batch['targets']
x_hat = self.model(x)
self.fc_outputs.append(x_hat)
output = nn.CrossEntropyLoss()
loss= output(x_hat,y)
return loss
的值x_hat不會被洗掉,除非您del x_hat在別處明確呼叫BEFORE 分配這些值。在您已經將 的值分配x_hat給另一個變數的情況下(在您的情況下聽起來您想將其附加到串列中)與這些值關聯的記憶體地址不會被釋放,因為仍然有一個參考這些地址的變數即使在參考它們的原始變數之后(x_hat可能已被洗掉)。這樣,python 在記憶體參考方面相對安全,因為它在運行時動態計算何時不再需要記憶體地址/值。
uj5u.com熱心網友回復:
我能做到這一點使用avgpool層上的前鉤和節約每test_step輸出等中描述的在這里:
#Define Hook:
def get_features(name):
def hook(model, input, output):
features[name] = output.detach()
return hook
現在,當我加載我的模型時,我注冊了鉤子:
#Load resnet model:
def get_model():
model = models.resnet50(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2)
model.avgpool.register_forward_hook(get_features('feats')) #register the hook
return model
我不需要更改 pytorch 閃電模型的 init 而是測驗步驟功能:
FEATS = []
# placeholder for batch features
features = {}
class classifierModel(pl.LightningModule):
def __init__(self, model):
super().__init__()
self.model = model
self.learning_rate = 0.0001
def test_step(self, batch,batch_idx):
x= batch['image']
y = batch['targets']
x_hat = self.model(x)
FEATS.append(features['feats'].cpu().numpy()) #added this line to save output
現在我們有了FEATS[0].shape --> (16, 2048, 1, 1)我想要得到的輸出(16 是使用的批量大小)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/377469.html
標籤:机器学习 深度学习 火炬 pytorch-闪电
上一篇:BigQuery線性回歸引數
下一篇:創建entityManagerFactory.Unable構建HibernateSessionF.SchemaManagementException時出錯:多次遇到匯出識別符號[new_user]
