I designed a simple mlp model to train on 6k data samples.
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
And the model has been instantiated
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()
and hyperparameters:
num_epoch = 300 # 200e3//len(train_loader) learning_rate = 1e-3 batch_size = 64 device = torch.device("cuda") seed = 42 torch.manual_seed(42)
My implementation mainly follows this question. I saved the model as pretrained weights model_weights.pth
.
model
on the test data set is 96.80%
.
Then, I have another 50 samples (in finetune_loader
) on which I am trying to fine-tune the model:
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
I checked, the accuracy remains the same as before fine-tuning the model to 50 samples, and the output probabilities are also the same.
What could be the reason? Did I make some mistakes in fine-tuning the code?
You must reinitialize the optimizer with a new model (model_finetune object). Currently, as I can see in your code, it seems to still use the optimizer that is initialized with the old model weights - model.parameters().
The above is the detailed content of Why fine-tuning an MLP model on a small dataset still maintains the same test accuracy as pre-trained weights?. For more information, please follow other related articles on the PHP Chinese website!