gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
"With pytorch how can I get the number of model parameters ?"
- User
"With pytorch how can I get the number of model parameters ?"
- Assistant
In PyTorch, you can easily obtain the number of parameters in a model by using the
parameters()method of the model, combined with a simple loop or comprehension to sum up the parameters. Here’s a step-by-step example:pythonimport torch import torch.nn as nn # Define a simple neural network model class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 2) def forward(self, x): x = self.fc1(x) x = self.fc2(x) return x # Instantiate the model model = MyModel() # Calculate the number of parameters num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The number of trainable parameters in the model: {num_params}')