You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

2_logistic_regression_2.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import time
  2. import torch as t
  3. from torch import nn, optim
  4. from torch.autograd import Variable
  5. from torch.utils.data import DataLoader
  6. from torchvision import transforms
  7. from torchvision import datasets
  8. """
  9. Use pytorch nn.Module to implement logistic regression
  10. """
  11. # define hyper parameters
  12. batch_size = 32
  13. learning_rate = 1e-3
  14. num_epoches = 100
  15. # download/load MNIST dataset
  16. dataset_path = "../data/mnist"
  17. train_dataset = datasets.MNIST(
  18. root=dataset_path, train=True, transform=transforms.ToTensor(), download=True)
  19. test_dataset = datasets.MNIST(
  20. root=dataset_path, train=False, transform=transforms.ToTensor())
  21. train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
  22. test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
  23. # define Logistic Regression model
  24. class Logstic_Regression(nn.Module):
  25. def __init__(self, in_dim, n_class):
  26. super(Logstic_Regression, self).__init__()
  27. self.logstic = nn.Linear(in_dim, n_class)
  28. def forward(self, x):
  29. out = self.logstic(x)
  30. return out
  31. model = Logstic_Regression(28 * 28, 10) # model's input/output node size
  32. use_gpu = t.cuda.is_available() # GPU use or not
  33. if use_gpu: model = model.cuda()
  34. # define loss & optimizer
  35. criterion = nn.CrossEntropyLoss()
  36. optimizer = optim.SGD(model.parameters(), lr=learning_rate)
  37. # training
  38. for epoch in range(num_epoches):
  39. print('-' * 40)
  40. print('epoch {}'.format(epoch + 1))
  41. since = time.time()
  42. running_loss = 0.0
  43. running_acc = 0.0
  44. for i, data in enumerate(train_loader, 1):
  45. img, label = data
  46. img = img.view(img.size(0), -1) # convert input image to dimensions of (n, 28x28)
  47. if use_gpu:
  48. img = Variable(img).cuda()
  49. label = Variable(label).cuda()
  50. else:
  51. img = Variable(img)
  52. label = Variable(label)
  53. # forward calculation
  54. out = model(img)
  55. loss = criterion(out, label)
  56. running_loss += loss.data[0] * label.size(0)
  57. _, pred = t.max(out, 1)
  58. num_correct = (pred == label).sum()
  59. running_acc += float(num_correct.data[0])
  60. # bp
  61. optimizer.zero_grad()
  62. loss.backward()
  63. optimizer.step()
  64. if i % 300 == 0:
  65. print('[{}/{}] Loss: {:.6f}, Acc: {:.6f}'.format(
  66. epoch + 1, num_epoches, running_loss / (batch_size * i),
  67. running_acc / (batch_size * i)))
  68. print('Finish {} epoch, Loss: {:.6f}, Acc: {:.6f}'.format(
  69. epoch + 1, running_loss / (len(train_dataset)), running_acc / (len(
  70. train_dataset))))
  71. model.eval()
  72. eval_loss = 0.
  73. eval_acc = 0.
  74. for data in test_loader:
  75. img, label = data
  76. img = img.view(img.size(0), -1)
  77. if use_gpu:
  78. img = Variable(img, volatile=True).cuda()
  79. label = Variable(label, volatile=True).cuda()
  80. else:
  81. img = Variable(img, volatile=True)
  82. label = Variable(label, volatile=True)
  83. out = model(img)
  84. loss = criterion(out, label)
  85. eval_loss += loss.data[0] * label.size(0)
  86. _, pred = t.max(out, 1)
  87. num_correct = (pred == label).sum()
  88. eval_acc += float(num_correct.data[0])
  89. print('Test Loss: {:.6f}, Acc: {:.6f}'.format(
  90. eval_loss / (len(test_dataset)),
  91. eval_acc / (len(test_dataset))))
  92. print('Time:{:.1f} s'.format(time.time() - since))
  93. print()
  94. # save model's parameters
  95. #t.save(model.state_dict(), './model_LogsticRegression.pth')

机器学习越来越多应用到飞行器、机器人等领域,其目的是利用计算机实现类似人类的智能,从而实现装备的智能化与无人化。本课程旨在引导学生掌握机器学习的基本知识、典型方法与技术,通过具体的应用案例激发学生对该学科的兴趣,鼓励学生能够从人工智能的角度来分析、解决飞行器、机器人所面临的问题和挑战。本课程主要内容包括Python编程基础,机器学习模型,无监督学习、监督学习、深度学习基础知识与实现,并学习如何利用机器学习解决实际问题,从而全面提升自我的《综合能力》。