PyTorch学习-多分类问题

Loss function-Cross Entropy L o s s ( Y ^ , Y ) = − Y l o g Y ^ Loss(\hat{Y},Y)=-Ylog\hat{Y}

Torch.nn.CrossEntropyLoss() ：包含了softmax和Loss

import torch
criterion = torch.nn.CrossEntropyLoss()
Y = torch.LongTensor([2,0,1]) # 输入LongTensor

Y_pred1 = torch.Tensor([[0.1, 0.2, 0.9],
[1.1, 0.1, 0.2],
[0.2, 2.1, 0.1]])
Y_pred2 = torch.Tensor([[0.8, 0.2, 0.3],
[0.2, 0.3, 0.5],
[0.2, 0.2, 0.5]])
loss1 = criterion(Y_pred1, Y)
loss2 = criterion(Y_pred2, Y)
print("Batch Loss1 = ", loss1.data, "\nBatch Loss2 = ", loss2.data)


Batch Loss1 =  tensor(0.4966)
Batch Loss2 =  tensor(1.2389)


CrossEntropyLoss <==> LogSoftmax + NULLLoss

ransforms.ToTensor()
W × H × C W\times H\times C 变为 C × W × H C\times W\times H

tansfrms.Normalize:

import torch
from torchvision import transforms # 对输入的输入进行变换
from torchvision import datasets
import torch.nn.functional as F # 使用relu()作为激活函数
import torch.optim as optim

batch_size = 64
# 将0-255的数据变为0到1的图像张量，
# 通道：channel
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081, ))
])

train_dataset = datasets.MNIST(root='../dataset/mnist/',
train = True,
transform = transform)
shuffle = True,
batch_size = batch_size)

test_dataset = datasets.MNIST(root='../dataset/mnist/',
train = False,
transform = transform)
shuffle=False,
batch_size = batch_size)

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) # -1自动计算N,将(N,1, 28, 28) 变成 (N, 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))
return self.l5(x) # 最后一个不做激活
model = Net()

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr = 0.01, momentum = 0.5) # momentum：带冲量的优化算法

def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data

outputs = model(inputs) # 获得预测值，forward
loss = criterion(outputs, target) # 获得损失值
loss.backward() # backward
optimizer.step() # update

running_loss += loss.item() # 注意加上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
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, dim = 1) # 每一行的最大值下标
total += labels.size(0) # 测试了多少个数据
correct += (predicted == labels).sum().item() # 计算有多少个预测正确
print('Accuuracy on test set: %d %%' % (100 * correct / total)) # 输出正确率

if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()



[1,   300] loss: 2.210
[1,   600] loss: 0.913
[1,   900] loss: 0.411
Accuuracy on test set: 89 %
[2,   300] loss: 0.320
[2,   600] loss: 0.271
[2,   900] loss: 0.226
Accuuracy on test set: 93 %
[3,   300] loss: 0.194
[3,   600] loss: 0.163
[3,   900] loss: 0.160
Accuuracy on test set: 95 %
[4,   300] loss: 0.138
[4,   600] loss: 0.121
[4,   900] loss: 0.112
Accuuracy on test set: 96 %
[5,   300] loss: 0.095
[5,   600] loss: 0.096
[5,   900] loss: 0.095
Accuuracy on test set: 96 %
[6,   300] loss: 0.073
[6,   600] loss: 0.080
[6,   900] loss: 0.073
Accuuracy on test set: 96 %
[7,   300] loss: 0.058
[7,   600] loss: 0.060
[7,   900] loss: 0.066
Accuuracy on test set: 97 %
[8,   300] loss: 0.045
[8,   600] loss: 0.054
[8,   900] loss: 0.050
Accuuracy on test set: 97 %
[9,   300] loss: 0.040
[9,   600] loss: 0.041
[9,   900] loss: 0.040
Accuuracy on test set: 97 %
[10,   300] loss: 0.033
[10,   600] loss: 0.031
[10,   900] loss: 0.034
Accuuracy on test set: 97 %