• pytorch-09.多分类问题


    NLLLoss(Negative Log Likelihood Loss),最大似然函数。
    把Label对应的输出log_result值拿出来,求和取平均。
    ---------------------------------------------------------------------------------------
    CrossEntropyLoss交叉熵损失函数。
    一步执行完:softmax+log+NLLLoss合并起来了。

    NLLLoss


    CrossEntropyLoss


    softmax:


    CrossEntropyLoss示例:

    #torch.LongTensor是64位整型
    #torch.Tensor默认torch.FloatTensor,是32位浮点类型数据。
    #torch.tensor是一个类,用于生成一个单精度浮点类型的张量。
    1. import torch
    2. criterion = torch.nn.CrossEntropyLoss()
    3. Y = torch.LongTensor([2,0,1])
    4. Y_pred1 = torch.Tensor([
    5. [0.1,0.2,0.9],
    6. [1.1,0.1,0.2],
    7. [0.2,2.1,0.1]
    8. ])
    9. Y_pred2 = torch.Tensor([
    10. [0.8,0.2,0.3],
    11. [0.2,0.3,0.5],
    12. [0.2,0.2,0.5]
    13. ])
    14. l1 = criterion(Y_pred1,Y)
    15. l2 = criterion(Y_pred2,Y)
    16. print("Loss1 = ",l1.data.item(),"\nLoss2 = ",l2.data.item())


     mnist数据集实践

    1. #minst数据集的均值是0.1307,标准差是0.3081
    2. import torch
    3. from torchvision import transforms
    4. from torchvision import datasets
    5. from torch.utils.data import DataLoader
    6. import torch.nn.functional as F
    7. import torch.optim as optim
    8. batch_size = 64
    9. transform = transforms.Compose([
    10. transforms.ToTensor(),
    11. transforms.Normalize((0.1307),(0.3081))
    12. ])
    13. train_dataset = datasets.MNIST(root='../dataset/mnist/',train=True,download=True,transform=transform)
    14. train_loader = DataLoader(train_dataset,shuffle = True,batch_size=batch_size)
    15. test_dataset = datasets.MNIST(root='../dataset/mnist/',train=False,download=True,transform=transform)
    16. test_loader = DataLoader(train_dataset,shuffle = False,batch_size=batch_size)
    17. class Net(torch.nn.Module):
    18. def __init__(self):
    19. super(Net, self).__init__()
    20. self.l1 = torch.nn.Linear(784,512)
    21. self.l2 = torch.nn.Linear(512,256)
    22. self.l3 = torch.nn.Linear(256, 128)
    23. self.l4 = torch.nn.Linear(128, 64)
    24. self.l5 = torch.nn.Linear(64, 10)
    25. def forward(self,x):
    26. x = x.view(-1,784)
    27. x = F.relu(self.l1(x))
    28. x = F.relu(self.l2(x))
    29. x = F.relu(self.l3(x))
    30. x = F.relu(self.l4(x))
    31. return self.l5(x) #最后一层不做激活,不进行非线性变换
    32. model = Net()
    33. criterion = torch.nn.CrossEntropyLoss()
    34. optimizer = optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
    35. def train(epoch):
    36. running_loss = 0.0
    37. for batch_idx,data in enumerate(train_loader,0):
    38. inputs, target = data
    39. optimizer.zero_grad()
    40. #forward + backward + update
    41. outputs = model(inputs)
    42. loss = criterion(outputs,target)
    43. loss.backward()
    44. optimizer.step()
    45. running_loss +=loss.item()
    46. if batch_idx % 300 ==299:
    47. print('[%d,%5d]loss:%.3f'%(epoch+1,batch_idx+1,running_loss/300))
    48. running_loss = 0
    49. def test():
    50. correct = 0
    51. total = 0
    52. with torch.no_grad():
    53. for data in test_loader:
    54. images,labels = data
    55. outputs = model(images)
    56. _,predicted = torch.max(outputs.data,dim=1) #dim=1维度1,行是第0个维度,列是第1个维度
    57. total +=labels.size(0)
    58. correct +=(predicted==labels).sum().item()
    59. print('Accuracy on test set:%d %%'%(100*correct/total) )
    60. if __name__ == '__main__':
    61. for epoch in range(10):
    62. train(epoch)
    63. test()

    结果:

    [1,  300]loss:2.223
    [1,  600]loss:0.923
    [1,  900]loss:0.435
    Accuracy on test set:89 %
    [2,  300]loss:0.328
    [2,  600]loss:0.272
    [2,  900]loss:0.239
    Accuracy on test set:94 %
    [3,  300]loss:0.188
    [3,  600]loss:0.175
    [3,  900]loss:0.158
    Accuracy on test set:96 %
    [4,  300]loss:0.126
    [4,  600]loss:0.130
    [4,  900]loss:0.121
    Accuracy on test set:97 %
    [5,  300]loss:0.098
    [5,  600]loss:0.099
    [5,  900]loss:0.097
    Accuracy on test set:97 %
    [6,  300]loss:0.078
    [6,  600]loss:0.079
    [6,  900]loss:0.081
    Accuracy on test set:97 %
    [7,  300]loss:0.066
    [7,  600]loss:0.063
    [7,  900]loss:0.064
    Accuracy on test set:98 %
    [8,  300]loss:0.050
    [8,  600]loss:0.056
    [8,  900]loss:0.051
    Accuracy on test set:98 %
    [9,  300]loss:0.041
    [9,  600]loss:0.043
    [9,  900]loss:0.043
    Accuracy on test set:99 %
    [10,  300]loss:0.034
    [10,  600]loss:0.034
    [10,  900]loss:0.037
    Accuracy on test set:99 %

    Process finished with exit code 0
     

  • 相关阅读:
    CSS3_字体图标
    【玩转Redhat Linux 8.0系列 | 从命令行管理文件(二)】
    算法金 | 不愧是腾讯,问基础巨细节 。。。
    Grafana----Grafana快速体验
    力扣刷题-字符串-(※)重复的子字符串
    上周热点回顾(3.28-4.3)
    HTTP各版本差异
    “高级Vue状态管理 - Vuex的魅力与应用“
    从零实现ORM框架GeoORM-记录新增和查询-03
    C 标准库 - <signal.h>和<stdarg.h>详解
  • 原文地址:https://blog.csdn.net/m0_65188455/article/details/126149531