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_poly_fitting.py 1.7 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import numpy as np
  2. import torch
  3. from torch.autograd import Variable
  4. import matplotlib.pyplot as plt
  5. """
  6. Polynomial fitting by pytorch
  7. """
  8. # define the real model's parameters
  9. w_target = np.array([0.5, 3, 2.4])
  10. b_target = np.array([0.9])
  11. f_des = "y = %f + %f * x + %f * x^2 + %f * x^3" % (
  12. b_target[0],
  13. w_target[0], w_target[1], w_target[2])
  14. print(f_des)
  15. # draw the data
  16. x_sample = np.arange(-3, 3.1, 0.1)
  17. y_sample = b_target[0] + w_target[0]*x_sample + w_target[1]*x_sample**2 + w_target[2]*x_sample**3
  18. plt.plot(x_sample, y_sample, label="Real")
  19. plt.legend()
  20. plt.show()
  21. # construct variabels
  22. x_train = np.stack([x_sample**i for i in range(1, 4)], axis=1)
  23. x_train = torch.from_numpy(x_train).float()
  24. y_train = torch.from_numpy(y_sample).float().unsqueeze(1)
  25. # define model parameters
  26. w = Variable(torch.randn(3, 1).float(), requires_grad=True)
  27. b = Variable(torch.zeros(1).float(), requires_grad=True)
  28. x_train = Variable(x_train)
  29. y_train = Variable(y_train)
  30. # define the model function & loss function
  31. def polynomial(x):
  32. return torch.mm(x, w) + b
  33. def get_loss(y_pred, y):
  34. return torch.mean((y_pred-y)**2)
  35. # begin iterative optimization
  36. eta = 0.001
  37. for i in range(100):
  38. y_pred = polynomial(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.data.zero_()
  44. b.grad.data.zero_()
  45. if i % 10 == 0:
  46. print("epoch: %4d, loss: %f" % (i, loss.data[0]))
  47. # draw the results
  48. y_pred = polynomial(x_train)
  49. plt.plot(x_train.data.numpy()[:, 0], y_sample, label="Real", color='b')
  50. plt.plot(x_train.data.numpy()[:, 0], y_pred.data.numpy(), label="Fitting", color='r')
  51. plt.legend()
  52. plt.show()

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