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_linear_regression_1.py 1.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import numpy as np
  2. import torch
  3. from torch.autograd import Variable
  4. import matplotlib.pyplot as plt
  5. """
  6. Using pytorch to do linear regression
  7. """
  8. torch.manual_seed(2018)
  9. # model's real-parameters
  10. w_target = 3
  11. b_target = 10
  12. # generate data
  13. n_data = 100
  14. x_train = np.random.rand(n_data, 1)*20 - 10
  15. y_train = w_target*x_train + b_target + (np.random.randn(n_data, 1)*10-5.0)
  16. # draw the data
  17. plt.plot(x_train, y_train, 'bo')
  18. plt.show()
  19. # convert to tensor
  20. x_train = torch.from_numpy(x_train).float()
  21. y_train = torch.from_numpy(y_train).float()
  22. # define model parameters
  23. w = Variable(torch.randn(1).float(), requires_grad=True)
  24. b = Variable(torch.zeros(1).float(), requires_grad=True)
  25. # construct the linear model
  26. x_train = Variable(x_train)
  27. y_train = Variable(y_train)
  28. # define model's function
  29. def linear_model(x):
  30. return x*w + b
  31. # define the loss function
  32. def get_loss(y_pred, y):
  33. return torch.mean((y_pred - y)**2)
  34. # upgrade parameters
  35. eta = 1e-2
  36. n_epoch = 100
  37. for i in range(n_epoch):
  38. y_pred = linear_model(x_train)
  39. loss = get_loss(y_pred, y_train)
  40. loss.backward()
  41. w.data = w.data - eta*w.grad.data
  42. b.data = b.data - eta*b.grad.data
  43. w.grad.zero_()
  44. b.grad.zero_()
  45. if i % 10 == 0:
  46. print("epoch: %3d, loss: %f" % (i, loss.data[0]))
  47. # draw the results
  48. plt.plot(x_train.data.numpy(), y_train.data.numpy(), 'bo', label="Real")
  49. plt.plot(x_train.data.numpy(), y_pred.data.numpy(), 'ro', label="Estimated")
  50. plt.legend()
  51. plt.show()

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