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.2.py 6.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. # 生成两类数据
  16. for j in range(2):
  17. ix = range(N*j,N*(j+1))
  18. t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
  19. r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
  20. x[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  21. y[ix] = j
  22. plt.ylabel("x2")
  23. plt.xlabel("x1")
  24. # 绘出生成的数据
  25. for i in range(m):
  26. if y[i] == 0:
  27. plt.scatter(x[i, 0], x[i, 1], marker='8',c=0, s=40, cmap=plt.cm.Spectral)
  28. else:
  29. plt.scatter(x[i, 0], x[i, 1], marker='^',c=1, s=40)
  30. plt.savefig('fig-res-8.2.pdf')
  31. plt.show()
  32. # #尝试用逻辑回归解决
  33. # x = torch.from_numpy(x).float()
  34. # y = torch.from_numpy(y).float()
  35. # w = nn.Parameter(torch.randn(2, 1))
  36. # b = nn.Parameter(torch.zeros(1))
  37. # # [w,b]是模型的参数; 1e-1是学习速率
  38. # optimizer = torch.optim.SGD([w, b], 1e-1)
  39. # criterion = nn.BCEWithLogitsLoss()
  40. # def logistic_regression(x):
  41. # return torch.mm(x, w) + b
  42. # for e in range(100):
  43. # # 模型正向计算
  44. # out = logistic_regression(Variable(x))
  45. # # 计算误差
  46. # loss = criterion(out, Variable(y))
  47. # # 误差反传和参数更新
  48. # optimizer.zero_grad()
  49. # loss.backward()
  50. # optimizer.step()
  51. # if (e + 1) % 20 == 0:
  52. # print('epoch:{}, loss:{}'.format(e+1, loss.item()))
  53. # def plot_decision_boundary(model, x, y):
  54. # # Set min and max values and give it some padding
  55. # x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
  56. # y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
  57. # h = 0.01
  58. # # Generate a grid of points with distance h between them
  59. # xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,y_max, h))
  60. # # Predict the function value for the whole grid .c_ 按行连接两个矩阵,左右相加。
  61. # Z = model(np.c_[xx.ravel(), yy.ravel()])
  62. # Z = Z.reshape(xx.shape)
  63. # # Plot the contour and training examples
  64. # plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  65. # plt.ylabel("x2")
  66. # plt.xlabel("x1")
  67. # plt.scatter(x[:, 0], x[:, 1], c=y.reshape(-1), s=40, cmap=plt.cm.Spectral)
  68. # def plot_logistic(x):
  69. # x = Variable(torch.from_numpy(x).float())
  70. # out = F.sigmoid(logistic_regression(x))
  71. # out = (out > 0.5) * 1
  72. # return out.data.numpy()
  73. # plot_decision_boundary(lambda x: plot_logistic(x), x.numpy(), y.numpy())
  74. # plt.title('logistic regression')
  75. # plt.savefig('fig-res-8.3.pdf')
  76. # # 定义两层神经网络的参数
  77. # w1 = nn.Parameter(torch.randn(2, 4) * 0.01) # 输入维度为2, 隐藏层神经元个数4
  78. # b1 = nn.Parameter(torch.zeros(4))
  79. # w2 = nn.Parameter(torch.randn(4, 1) * 0.01) # 隐层神经元为4, 输出单元为1
  80. # b2 = nn.Parameter(torch.zeros(1))
  81. # def mlp_network(x):
  82. # x1 = torch.mm(x, w1) + b1
  83. # x1 = F.tanh(x1) # 使用 PyTorch 自带的 tanh 激活函数
  84. # x2 = torch.mm(x1, w2) + b2
  85. # return x2
  86. # # 定义优化器和损失函数
  87. # optimizer = torch.optim.SGD([w1, w2, b1, b2], 1.)
  88. # criterion = nn.BCEWithLogitsLoss()
  89. # for e in range(10000):
  90. # # 正向计算
  91. # out = mlp_network(Variable(x))
  92. # # 计算误差
  93. # loss = criterion(out, Variable(y))
  94. # # 计算梯度并更新权重
  95. # optimizer.zero_grad()
  96. # loss.backward()
  97. # optimizer.step()
  98. # if (e + 1) % 1000 == 0:
  99. # print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  100. # def plot_network(x):
  101. # x = Variable(torch.from_numpy(x).float())
  102. # x1 = torch.mm(x, w1) + b1
  103. # x1 = F.tanh(x1)
  104. # x2 = torch.mm(x1, w2) + b2
  105. # out = F.sigmoid(x2)
  106. # out = (out > 0.5) * 1
  107. # return out.data.numpy()
  108. # plot_decision_boundary(lambda x: plot_network(x), x.numpy(), y.numpy())
  109. # plt.title('2 layer network')
  110. # plt.savefig('fig-res-8.4.pdf')
  111. # # Sequential
  112. # seq_net = nn.Sequential(
  113. # nn.Linear(2, 4), # PyTorch 中的线性层, wx + b
  114. # nn.Tanh(),
  115. # nn.Linear(4, 1)
  116. # )
  117. # # 序列模块可以通过索引访问每一层
  118. # seq_net[0] # 第一层
  119. # # 打印出第一层的权重
  120. # w0 = seq_net[0].weight
  121. # print(w0)
  122. # # 通过 parameters 可以取得模型的参数
  123. # param = seq_net.parameters()
  124. # # 定义优化器
  125. # optim = torch.optim.SGD(param, 1.)
  126. # # 训练 10000 次
  127. # for e in range(10000):
  128. # # 网络正向计算
  129. # out = seq_net(Variable(x))
  130. # # 计算误差
  131. # loss = criterion(out, Variable(y))
  132. # # 反向传播、 更新权重
  133. # optim.zero_grad()
  134. # loss.backward()
  135. # optim.step()
  136. # # 打印损失
  137. # if (e + 1) % 1000 == 0:
  138. # print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  139. # def plot_seq(x):
  140. # out = F.sigmoid(seq_net(Variable(torch.from_numpy(x).float()))).data.numpy()
  141. # out = (out > 0.5) * 1
  142. # return out
  143. # plot_decision_boundary(lambda x: plot_seq(x), x.numpy(), y.numpy())
  144. # plt.title('sequential')
  145. # plt.savefig('fig-res-8.5.pdf')
  146. # torch.save(seq_net, 'save_seq_net.pth')
  147. # # 读取保存的模型
  148. # seq_net1 = torch.load('save_seq_net.pth')
  149. # # 打印加载的模型
  150. # seq_net1
  151. # print(seq_net1[0].weight)
  152. # # 保存模型参数
  153. # torch.save(seq_net.state_dict(), 'save_seq_net_params.pth')
  154. # # 定义网络架构
  155. # seq_net2 = nn.Sequential(
  156. # nn.Linear(2, 4),
  157. # nn.Tanh(),
  158. # nn.Linear(4, 1)
  159. # )
  160. # # 加载网络参数
  161. # seq_net2.load_state_dict(torch.load('save_seq_net_params.pth'))
  162. # # 打印网络结构
  163. # seq_net2
  164. # print(seq_net2[0].weight)
  165. # class Module_Net(nn.Module):
  166. # def __init__(self, num_input, num_hidden, num_output):
  167. # super(Module_Net, self).__init__()
  168. # self.layer1 = nn.Linear(num_input, num_hidden)
  169. # self.layer2 = nn.Tanh()
  170. # self.layer3 = nn.Linear(num_hidden, num_output)
  171. # def forward(self, x):
  172. # x = self.layer1(x)
  173. # x = self.layer2(x)
  174. # x = self.layer3(x)
  175. # return x
  176. # mo_net = Module_Net(2, 4, 1)
  177. # # 访问模型中的某层可以直接通过名字, 网络第一层
  178. # l1 = mo_net.layer1
  179. # print(l1)
  180. # optim = torch.optim.SGD(mo_net.parameters(), 1.)
  181. # # 训练 10000 次
  182. # for e in range(10000):
  183. # # 网络正向计算
  184. # out = mo_net(Variable(x))
  185. # # 计算误差
  186. # loss = criterion(out, Variable(y))
  187. # # 误差反传、 更新参数
  188. # optim.zero_grad()
  189. # loss.backward()
  190. # optim.step()
  191. # # 打印损失
  192. # if (e + 1) % 1000 == 0:
  193. # print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  194. # torch.save(mo_net.state_dict(), 'module_net.pth')

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