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.

fig-res-8.6.py 3.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import torch
  2. import numpy as np
  3. from torch import nn
  4. from torch.autograd import Variable
  5. import torch.nn.functional as F
  6. import matplotlib.pyplot as plt
  7. #%matplotlib inline
  8. np.random.seed(1)
  9. m = 400 # 样本数量
  10. N = int(m/2) # 每一类的点的个数
  11. D = 2 # 维度
  12. x = np.zeros((m, D))
  13. y = np.zeros((m, 1), dtype='uint8') # label 向量, 0 表示红色, 1 表示蓝色
  14. a = 4
  15. criterion = nn.BCEWithLogitsLoss()
  16. # 生成两类数据
  17. for j in range(2):
  18. ix = range(N*j,N*(j+1))
  19. t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
  20. r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
  21. x[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  22. y[ix] = j
  23. def plot_decision_boundary(model, x, y):
  24. # Set min and max values and give it some padding
  25. x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
  26. y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
  27. h = 0.01
  28. # Generate a grid of points with distance h between them
  29. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,y_max, h))
  30. # Predict the function value for the whole grid .c_ 按行连接两个矩阵,左右相加。
  31. Z = model(np.c_[xx.ravel(), yy.ravel()])
  32. Z = Z.reshape(xx.shape)
  33. # Plot the contour and training examples
  34. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  35. plt.ylabel("x2")
  36. plt.xlabel("x1")
  37. for i in range(m):
  38. if y[i] == 0:
  39. plt.scatter(x[i, 0], x[i, 1], marker='8',c=0, s=40, cmap=plt.cm.Spectral)
  40. else:
  41. plt.scatter(x[i, 0], x[i, 1], marker='^',c=1, s=40)
  42. #尝试用逻辑回归解决
  43. x = torch.from_numpy(x).float()
  44. y = torch.from_numpy(y).float()
  45. seq_net = nn.Sequential(
  46. nn.Linear(2, 4), # PyTorch 中的线性层, wx + b
  47. nn.Tanh(),
  48. nn.Linear(4, 1)
  49. )
  50. # 读取保存的模型
  51. seq_net1 = torch.load('save_seq_net.pth')
  52. # 打印加载的模型
  53. seq_net1
  54. print(seq_net1[0].weight)
  55. # 保存模型参数
  56. torch.save(seq_net.state_dict(), 'save_seq_net_params.pth')
  57. # 定义网络架构
  58. seq_net2 = nn.Sequential(
  59. nn.Linear(2, 4),
  60. nn.Tanh(),
  61. nn.Linear(4, 1)
  62. )
  63. # 加载网络参数
  64. seq_net2.load_state_dict(torch.load('save_seq_net_params.pth'))
  65. # 打印网络结构
  66. seq_net2
  67. print(seq_net2[0].weight)
  68. class Module_Net(nn.Module):
  69. def __init__(self, num_input, num_hidden, num_output):
  70. super(Module_Net, self).__init__()
  71. self.layer1 = nn.Linear(num_input, num_hidden)
  72. self.layer2 = nn.Tanh()
  73. self.layer3 = nn.Linear(num_hidden, num_output)
  74. def forward(self, x):
  75. x = self.layer1(x)
  76. x = self.layer2(x)
  77. x = self.layer3(x)
  78. return x
  79. mo_net = Module_Net(2, 4, 1)
  80. # 访问模型中的某层可以直接通过名字, 网络第一层
  81. l1 = mo_net.layer1
  82. print(l1)
  83. optim = torch.optim.SGD(mo_net.parameters(), 1.)
  84. # 训练 10000 次
  85. for e in range(10000):
  86. # 网络正向计算
  87. out = mo_net(Variable(x))
  88. # 计算误差
  89. loss = criterion(out, Variable(y))
  90. # 误差反传、 更新参数
  91. optim.zero_grad()
  92. loss.backward()
  93. optim.step()
  94. # 打印损失
  95. if (e + 1) % 1000 == 0:
  96. print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  97. torch.save(mo_net.state_dict(), 'module_net.pth')

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