在PyTorch中,我们可以使用torchvision.transforms
模块中的ToTensor()
函数将图像数据转换为PyTorch张量,然后使用nn.Linear()
层来提取特征。以下是一个简单的示例:
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
# 加载MNIST数据集
transform = transforms.Compose([transforms.ToTensor()])
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)
# 定义一个简单的神经网络
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28 * 28, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001)
# 训练网络
for epoch in range(5):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch + 1}, Loss: {running_loss / (i + 1)}")
print("Finished Training")
在这个示例中,我们首先加载MNIST数据集并将其转换为PyTorch张量。然后,我们定义了一个简单的神经网络,其中包含一个输入层、两个隐藏层和一个输出层。在输入层中,我们将输入图像展平为一维向量(28 * 28),然后将其传递给隐藏层。最后,我们使用交叉熵损失函数和随机梯度下降优化器训练网络。