玉桂狗是一個神經網絡模型,用于圖像識別任務。以下是一個簡單的示例代碼,用于訓練和測試玉桂狗模型。
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定義玉桂狗模型
class JadeDog(nn.Module):
def __init__(self):
super(JadeDog, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(64 * 8 * 8, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(-1, 64 * 8 * 8)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 數據預處理和加載
transform = transforms.Compose([
transforms.RandomHorizontalFlip(), # 隨機水平翻轉
transforms.ToTensor(), # 轉為張量
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 標準化
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
# 初始化模型和優化器
model = JadeDog()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
criterion = nn.CrossEntropyLoss()
# 訓練模型
def train(model, optimizer, criterion, train_loader):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
# 測試模型
def test(model, criterion, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = 100. * correct / len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset), accuracy))
# 開始訓練和測試
for epoch in range(1, 11):
train(model, optimizer, criterion, train_loader)
test(model, criterion, test_loader)
以上代碼使用PyTorch庫構建了一個簡單的玉桂狗模型,并使用CIFAR-10數據集進行訓練和測試。你可以根據實際需要進行修改和擴展。