主题
多分类问题
总结
多分类问题各个分量的输出应该是相互抑制的,带有竞争性的。
softmax层中同层的节点输入会影响当前节点的输出。
CrossEntropyLoss = LogSoftmax + NLLLOSS。采用CrossEntropyLoss中包含有LogSoftmax激活层,所以模型的最后一层不设置激活
transform = transforms.Compose([··· , ···])
: 建立dataset时传入的参数,用于图像变换。python读取图像的格式是PIL图像文件中像素存储结构是WHC,需要转换成CWH
transforms.Normalize(( , ) , ( , ))
:把数据变换至标准正态分布x = x.view(-1, 28*28)
:数据尺寸转换节点,把图片平铺使得可以作为nn.Linear的输入
代码
接下来介绍完整代码,分为:
- 导入模块
- 主代码
- 数据准备
- 定义模型
- 创建模型、损失函数节点、优化器
- 定义训练/测试过程
- 执行结果
1. 导入模块
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch
2. 主代码
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()
3. 数据准备
batch_size = 64
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='../dataset/mnist/',
train=True,
download=True,
transform=transform)
train_loader = DataLoader(train_dataset,
shuffle=True,
batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist/',
train=False,
download=True,
transform=transform)
test_loader = DataLoader(test_dataset,
shuffle=False,
batch_size=batch_size)
4. 定义模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.l1 = torch.nn.Linear(784, 512)
self.l2 = torch.nn.Linear(512, 256)
self.l3 = torch.nn.Linear(256, 128)
self.l4 = torch.nn.Linear(128, 64)
self.l5 = torch.nn.Linear(64, 10)
def forward(self, x):
x = x.view(-1, 784)
x = F.relu(self.l1(x))
x = F.relu(self.l2(x))
x = F.relu(self.l3(x))
x = F.relu(self.l4(x))
x = self.l5(x)
return x
5. 创建模型、损失函数节点、优化器
model = Net()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
6. 定义训练/测试过程
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[%d, %5d] Loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
running_loss = 0.0
def test():
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predict = torch.max(outputs.data, dim=1)
total += labels.size(0)
correct += (predict == labels).sum().item()
print('Accuracy on test set:%d %%' % (100 * correct/total))
7. 执行结果
[1, 300] Loss: 2.227
[1, 600] Loss: 1.038
[1, 900] Loss: 0.436
Accuracy on test set:89 %
[2, 300] Loss: 0.329
[2, 600] Loss: 0.273
[2, 900] Loss: 0.247
Accuracy on test set:94 %
[3, 300] Loss: 0.197
[3, 600] Loss: 0.175
[3, 900] Loss: 0.158
Accuracy on test set:95 %
[4, 300] Loss: 0.135
[4, 600] Loss: 0.125
[4, 900] Loss: 0.116
Accuracy on test set:96 %
[5, 300] Loss: 0.095
[5, 600] Loss: 0.098
[5, 900] Loss: 0.094
Accuracy on test set:96 %
[6, 300] Loss: 0.074
[6, 600] Loss: 0.078
[6, 900] Loss: 0.075
Accuracy on test set:97 %
[7, 300] Loss: 0.062
[7, 600] Loss: 0.060
[7, 900] Loss: 0.058
Accuracy on test set:96 %
[8, 300] Loss: 0.048
[8, 600] Loss: 0.052
[8, 900] Loss: 0.048
Accuracy on test set:97 %
[9, 300] Loss: 0.037
[9, 600] Loss: 0.042
[9, 900] Loss: 0.041
Accuracy on test set:97 %
[10, 300] Loss: 0.032
[10, 600] Loss: 0.035
[10, 900] Loss: 0.032
Accuracy on test set:97 %
Process finished with exit code 0