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.

Linear_Regression.py 1.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import torch as t
  2. from torch import nn, optim
  3. from torch.autograd import Variable
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. # create numpy data
  7. x_train = np.linspace(0, 10, 100)
  8. y_train = 10*x_train + 4.5
  9. # convert to tensor (need to change nx1, float32 dtype)
  10. x_train = t.from_numpy(x_train.reshape(-1, 1).astype("float32"))
  11. y_train = t.from_numpy(y_train.reshape(-1, 1).astype("float32"))
  12. # Linear Regression Model
  13. class LinearRegression(nn.Module):
  14. def __init__(self):
  15. super(LinearRegression, self).__init__()
  16. self.linear = nn.Linear(1, 1) # input and output is 1 dimension
  17. def forward(self, x):
  18. out = self.linear(x)
  19. return out
  20. # create the model
  21. model = LinearRegression()
  22. # 定义loss和优化函数
  23. criterion = nn.MSELoss()
  24. optimizer = optim.SGD(model.parameters(), lr=1e-4)
  25. # 开始训练
  26. num_epochs = 1000
  27. for epoch in range(num_epochs):
  28. inputs = Variable(x_train)
  29. target = Variable(y_train)
  30. # forward
  31. out = model(inputs)
  32. loss = criterion(out, target)
  33. # backward
  34. optimizer.zero_grad()
  35. loss.backward()
  36. optimizer.step()
  37. if (epoch+1) % 20 == 0:
  38. print('Epoch[{}/{}], loss: {:.6f}'
  39. .format(epoch+1, num_epochs, loss.data[0]))
  40. model.eval()
  41. predict = model(Variable(x_train))
  42. predict = predict.data.numpy()
  43. plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
  44. plt.plot(x_train.numpy(), predict, label='Fitting Line')
  45. # 显示图例
  46. plt.legend()
  47. plt.show()
  48. # 保存模型
  49. t.save(model.state_dict(), './model_LinearRegression.pth')

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