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.5.py 3.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. import matplotlib as mpl
  8. plt.rcParams['font.sans-serif']=['SimHei']
  9. plt.rcParams['axes.unicode_minus'] = False
  10. #%matplotlib inline
  11. np.random.seed(1)
  12. m = 400 # 样本数量
  13. N = int(m/2) # 每一类的点的个数
  14. D = 2 # 维度
  15. x = np.zeros((m, D))
  16. y = np.zeros((m, 1), dtype='uint8') # label 向量, 0 表示红色, 1 表示蓝色
  17. a = 4
  18. criterion = nn.BCEWithLogitsLoss()
  19. # 生成两类数据
  20. for j in range(2):
  21. ix = range(N*j,N*(j+1))
  22. t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
  23. r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
  24. x[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  25. y[ix] = j
  26. def plot_decision_boundary(model, x, y):
  27. # Set min and max values and give it some padding
  28. x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
  29. y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
  30. h = 0.01
  31. # Generate a grid of points with distance h between them
  32. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,y_max, h))
  33. # Predict the function value for the whole grid .c_ 按行连接两个矩阵,左右相加。
  34. Z = model(np.c_[xx.ravel(), yy.ravel()])
  35. Z = Z.reshape(xx.shape)
  36. # Plot the contour and training examples
  37. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  38. plt.ylabel("x2")
  39. plt.xlabel("x1")
  40. for i in range(m):
  41. if y[i] == 0:
  42. plt.scatter(x[i, 0], x[i, 1], marker='8',c=0, s=40, cmap=plt.cm.Spectral)
  43. else:
  44. plt.scatter(x[i, 0], x[i, 1], marker='^',c=1, s=40)
  45. #尝试用逻辑回归解决
  46. x = torch.from_numpy(x).float()
  47. y = torch.from_numpy(y).float()
  48. # Sequential
  49. seq_net = nn.Sequential(
  50. nn.Linear(2, 4), # PyTorch 中的线性层, wx + b
  51. nn.Tanh(),
  52. nn.Linear(4, 1)
  53. )
  54. # 序列模块可以通过索引访问每一层
  55. seq_net[0] # 第一层
  56. # 打印出第一层的权重
  57. w0 = seq_net[0].weight
  58. print(w0)
  59. # 通过 parameters 可以取得模型的参数
  60. param = seq_net.parameters()
  61. # 定义优化器
  62. optim = torch.optim.SGD(param, 1.)
  63. # 训练 10000 次
  64. for e in range(10000):
  65. # 网络正向计算
  66. out = seq_net(Variable(x))
  67. # 计算误差
  68. loss = criterion(out, Variable(y))
  69. # 反向传播、 更新权重
  70. optim.zero_grad()
  71. loss.backward()
  72. optim.step()
  73. # 打印损失
  74. if (e + 1) % 1000 == 0:
  75. print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  76. def plot_seq(x):
  77. out = F.sigmoid(seq_net(Variable(torch.from_numpy(x).float()))).data.numpy()
  78. out = (out > 0.5) * 1
  79. return out
  80. plot_decision_boundary(lambda x: plot_seq(x), x.numpy(), y.numpy())
  81. mpl.rcParams['font.family'] = 'SimHei'
  82. plt.rcParams['axes.unicode_minus'] = False
  83. # plt.title('序列化网络')
  84. # plt.savefig('fig-res-8.5.pdf')
  85. plt.title('模块定义网络')
  86. plt.savefig('fig-res-8.6.pdf')
  87. plt.show()
  88. torch.save(seq_net, 'save_seq_net.pth')

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