好莱坞明星识别是一个常见的计算机视觉问题,可以使用PyTorch实现。在本文中,我们将介绍如何使用PyTorch实现好莱坞明星识别,并提供两个示例说明。
示例一:使用PyTorch实现好莱坞明星识别
我们可以使用PyTorch实现好莱坞明星识别。示例代码如下:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models
# 定义超参数
num_epochs = 10
batch_size = 8
learning_rate = 0.001
# 加载数据集
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = 'path/to/data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
data_transforms[x])
for x in ['train', 'val']}
dataloaders = {x: DataLoader(image_datasets[x], batch_size=batch_size,
shuffle=True, num_workers=4)
for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
# 加载预训练模型
model = models.resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, len(class_names))
model = model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
print('Finished Training')
在上述代码中,我们首先加载了数据集,并定义了一个预训练的ResNet18模型。然后,我们定义了损失函数和优化器,并使用训练集训练模型。最后,我们使用测试集测试模型的准确率。
示例二:使用PyTorch实现好莱坞明星识别(迁移学习)
除了使用预训练模型,我们还可以使用迁移学习来实现好莱坞明星识别。示例代码如下:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models
# 定义超参数
num_epochs = 10
batch_size = 8
learning_rate = 0.001
# 加载数据集
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
data_dir = 'path/to/data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
data_transforms[x])
for x in ['train', 'val']}
dataloaders = {x: DataLoader(image_datasets[x], batch_size=batch_size,
shuffle=True, num_workers=4)
for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
# 加载预训练模型
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, len(class_names))
# 冻结模型的所有层
for param in model_ft.parameters():
param.requires_grad = False
# 解冻最后一层
for param in model_ft.fc.parameters():
param.requires_grad = True
model_ft = model_ft.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model_ft.fc.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
for phase in ['train', 'val']:
if phase == 'train':
model_ft.train()
else:
model_ft.eval()
running_loss = 0.0
running_corrects = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer_ft.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model_ft(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer_ft.step()
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
print('Finished Training')
在上述代码中,我们首先加载了数据集,并定义了一个预训练的ResNet18模型。然后,我们冻结了模型的所有层,并解冻了最后一层。接着,我们定义了损失函数和优化器,并使用训练集训练模型。最后,我们使用测试集测试模型的准确率。
总结
本文介绍了如何使用PyTorch实现好莱坞明星识别,并提供了两个示例说明。我们可以使用预训练模型或迁移学习来实现好莱坞明星识别。我们可以使用PyTorch的nn.Module类定义模型,使用nn.CrossEntropyLoss()函数定义损失函数,使用optim.SGD()函数定义优化器,使用backward()函数进行反向传播,使用step()函数更新参数。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:pytorch实现好莱坞明星识别的示例代码 - Python技术站