為什麼在小資料集上微調 MLP 模型,仍然保持與預訓練權重相同的測試精度?

WBOY
發布: 2024-02-10 21:36:04
轉載
566 人瀏覽過

为什么在小数据集上微调 MLP 模型,仍然保持与预训练权重相同的测试精度?

問題內容

我設計了一個簡單的 mlp 模型,在 6k 資料樣本上訓練。

class mlp(nn.module):
    def __init__(self,input_dim=92, hidden_dim = 150, num_classes=2):
        super().__init__()
        self.input_dim = input_dim
        self.num_classes = num_classes
        self.hidden_dim = hidden_dim
        #self.softmax = nn.softmax(dim=1)

        self.layers = nn.sequential(
            nn.linear(self.input_dim, self.hidden_dim),
            nn.relu(),
            nn.linear(self.hidden_dim, self.hidden_dim),
            nn.relu(),
            nn.linear(self.hidden_dim, self.hidden_dim),
            nn.relu(),
            nn.linear(self.hidden_dim, self.num_classes),

        )

    def forward(self, x):
        x = self.layers(x)
        return x
登入後複製

並且模型已實例化

model = mlp(input_dim=input_dim, hidden_dim=hidden_dim, num_classes=num_classes).to(device)

optimizer = optimizer.adam(model.parameters(), lr=learning_rate, weight_decay=1e-4)
criterion = nn.crossentropyloss()
登入後複製

和超參數:

num_epoch = 300   # 200e3//len(train_loader)
learning_rate = 1e-3
batch_size = 64
device = torch.device("cuda")
seed = 42
torch.manual_seed(42)
登入後複製

我的實作主要遵循這個問題。我將模型儲存為預訓練權重 model_weights.pth

model在測試資料集上的準確率是96.80%

然後,我還有另外 50 個樣本(在 finetune_loader 中),我正在嘗試在這 50 個樣本上微調模型:

model_finetune = MLP()
model_finetune.load_state_dict(torch.load('model_weights.pth'))
model_finetune.to(device)
model_finetune.train()
# train the network
for t in tqdm(range(num_epoch)):
  for i, data in enumerate(finetune_loader, 0):
    #def closure():
      # Get and prepare inputs
      inputs, targets = data
      inputs, targets = inputs.float(), targets.long()
      inputs, targets = inputs.to(device), targets.to(device)
      
      # Zero the gradients
      optimizer.zero_grad()
      # Perform forward pass
      outputs = model_finetune(inputs)
      # Compute loss
      loss = criterion(outputs, targets)
      # Perform backward pass
      loss.backward()
      #return loss
      optimizer.step()     # a

model_finetune.eval()
with torch.no_grad():
    outputs2 = model_finetune(test_data)
    #predicted_labels = outputs.squeeze().tolist()

    _, preds = torch.max(outputs2, 1)
    prediction_test = np.array(preds.cpu())
    accuracy_test_finetune = accuracy_score(y_test, prediction_test)
    accuracy_test_finetune
    
    Output: 0.9680851063829787
登入後複製

我檢查過,精度與將模型微調到 50 個樣本之前保持不變,並且輸出機率也相同。

可能是什麼原因?我在微調程式碼中是否犯了一些錯誤?


正確答案


您必須使用新模型(model_finetune 物件)重新初始化優化器。目前,正如我在您的程式碼中看到的那樣,它似乎仍然使用使用舊模型權重初始化的優化器 - model.parameters()。

以上是為什麼在小資料集上微調 MLP 模型,仍然保持與預訓練權重相同的測試精度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!