Ques:- How do you perform transfer learning in PyTorch
Asked In :-
Zessta Software Services, Nalsoft, Relinns Technologies, rdc concrete (india) pvt ltd, agilisium consulting, palle technologies,
Right Answer:
To perform transfer learning in PyTorch, follow these steps:
1. **Load a Pre-trained Model**: Use a model from `torchvision.models`, e.g., `model = torchvision.models.resnet18(pretrained=True)`.
2. **Modify the Final Layer**: Replace the final layer to match the number of classes in your dataset:
```python
num_classes = 10 # Example for 10 classes
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
```
3. **Freeze Layers (Optional)**: Freeze the weights of the earlier layers if you want to retain their learned features:
```python
for param in model.parameters():
param.requires_grad = False
for param in model.fc.parameters():
param.requires_grad = True
```
4. **Set Up the Loss Function and Optimizer**:
```python
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD
To perform transfer learning in PyTorch, follow these steps:
1. **Load a Pre-trained Model**: Use a model from `torchvision.models`, e.g., `model = torchvision.models.resnet18(pretrained=True)`.
2. **Modify the Final Layer**: Replace the final layer to match the number of classes in your dataset:
```python
num_classes = 10 # Example for 10 classes
model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
```
3. **Freeze Layers (Optional)**: Freeze the weights of the earlier layers if you want to retain their learned features:
```python
for param in model.parameters():
param.requires_grad = False
for param in model.fc.parameters():
param.requires_grad = True
```
4. **Set Up the Loss Function and Optimizer**:
```python
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD