pytorch人脸表情识别代码
时间: 2024-03-29 14:33:02 浏览: 113
PyTorch是一个开源的深度学习框架,可以用于构建和训练神经网络模型。人脸表情识别是一个常见的计算机视觉任务,可以通过PyTorch来实现。
以下是一个简单的PyTorch人脸表情识别代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# 定义神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.fc1 = nn.Linear(64 * 5 * 5, 128)
self.fc2 = nn.Linear(128, 7) # 7个表情类别
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = nn.functional.relu(self.conv2(x))
x = x.view(-1, 64 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 数据预处理和加载
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
train_dataset = datasets.FER2013(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.FER2013(root='./data', train=False, transform=transform, download=True)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
# 初始化模型和优化器
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 10
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for epoch in range(num_epochs):
model.train()
for batch_idx, (data, targets) in enumerate(train_loader):
data = data.to(device)
targets = targets.to(device)
# 前向传播和计算损失
outputs = model(data)
loss = criterion(outputs, targets)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 在测试集上评估模型性能
model.eval()
with torch.no_grad():
correct = 0
total = 0
for data, targets in test_loader:
data = data.to(device)
targets = targets.to(device)
outputs = model(data)
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += (predicted == targets).sum().item()
accuracy = 100 * correct / total
print(f"Epoch [{epoch+1}/{num_epochs}], Test Accuracy: {accuracy:.2f}%")
# 保存模型
torch.save(model.state_dict(), 'emotion_model.pth')
```
这段代码实现了一个简单的卷积神经网络模型,用于人脸表情识别。它使用FER2013数据集进行训练和测试,并在每个epoch结束时输出测试集的准确率。最后,模型会被保存为`emotion_model.pth`文件。
阅读全文