pytorch用Resnet进行人脸识别的代码
时间: 2024-01-07 08:05:05 浏览: 113
以下是使用 PyTorch 和 ResNet 进行人脸识别的代码:
```python
import torch
import torch.nn as nn
import torchvision.models as models
# 加载 ResNet 模型
resnet = models.resnet18(pretrained=True)
# 冻结 ResNet 的所有层
for param in resnet.parameters():
param.requires_grad = False
# 将最后一层的输出特征数修改为人脸的类别数
num_classes = 10
resnet.fc = nn.Linear(resnet.fc.in_features, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(resnet.fc.parameters())
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
outputs = resnet(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = resnet(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))
```
在这个代码中,我们使用了一个预先训练好的 ResNet-18 模型,将其最后一层的输出特征数修改为我们需要分类的类别数,并且只训练了最后一层的参数。在训练期间,我们使用交叉熵损失函数和 Adam 优化器来更新模型的参数。在测试期间,我们使用测试集来评估模型的准确性。
阅读全文