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.4.py 2.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. plt.rcParams['font.sans-serif']=['SimHei']
  8. plt.rcParams['axes.unicode_minus'] = False
  9. #%matplotlib inline
  10. np.random.seed(1)
  11. m = 400 # 样本数量
  12. N = int(m/2) # 每一类的点的个数
  13. D = 2 # 维度
  14. x = np.zeros((m, D))
  15. y = np.zeros((m, 1), dtype='uint8') # label 向量, 0 表示红色, 1 表示蓝色
  16. a = 4
  17. # 生成两类数据
  18. for j in range(2):
  19. ix = range(N*j,N*(j+1))
  20. t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
  21. r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
  22. x[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  23. y[ix] = j
  24. x = torch.from_numpy(x).float()
  25. y = torch.from_numpy(y).float()
  26. # 定义两层神经网络的参数
  27. w1 = nn.Parameter(torch.randn(2, 4) * 0.01) # 输入维度为2, 隐藏层神经元个数4
  28. b1 = nn.Parameter(torch.zeros(4))
  29. w2 = nn.Parameter(torch.randn(4, 1) * 0.01) # 隐层神经元为4, 输出单元为1
  30. b2 = nn.Parameter(torch.zeros(1))
  31. def mlp_network(x):
  32. x1 = torch.mm(x, w1) + b1
  33. x1 = F.tanh(x1) # 使用 PyTorch 自带的 tanh 激活函数
  34. x2 = torch.mm(x1, w2) + b2
  35. return x2
  36. # 定义优化器和损失函数
  37. optimizer = torch.optim.SGD([w1, w2, b1, b2], 1.)
  38. criterion = nn.BCEWithLogitsLoss()
  39. for e in range(10000):
  40. # 正向计算
  41. out = mlp_network(Variable(x))
  42. # 计算误差
  43. loss = criterion(out, Variable(y))
  44. # 计算梯度并更新权重
  45. optimizer.zero_grad()
  46. loss.backward()
  47. optimizer.step()
  48. if (e + 1) % 1000 == 0:
  49. print('epoch: {}, loss: {}'.format(e+1, loss.item()))
  50. def plot_decision_boundary(model, x, y):
  51. # Set min and max values and give it some padding
  52. x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
  53. y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
  54. h = 0.01
  55. # Generate a grid of points with distance h between them
  56. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,y_max, h))
  57. # Predict the function value for the whole grid .c_ 按行连接两个矩阵,左右相加。
  58. Z = model(np.c_[xx.ravel(), yy.ravel()])
  59. Z = Z.reshape(xx.shape)
  60. # Plot the contour and training examples
  61. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  62. plt.ylabel("x2")
  63. plt.xlabel("x1")
  64. for i in range(m):
  65. if y[i] == 0:
  66. plt.scatter(x[i, 0], x[i, 1], marker='8',c=0, s=40, cmap=plt.cm.Spectral)
  67. else:
  68. plt.scatter(x[i, 0], x[i, 1], marker='^',c=1, s=40)
  69. def plot_network(x):
  70. x = Variable(torch.from_numpy(x).float())
  71. x1 = torch.mm(x, w1) + b1
  72. x1 = F.tanh(x1)
  73. x2 = torch.mm(x1, w2) + b2
  74. out = F.sigmoid(x2)
  75. out = (out > 0.5) * 1
  76. return out.data.numpy()
  77. plot_decision_boundary(lambda x: plot_network(x), x.numpy(), y.numpy())
  78. plt.title('2层神经网络')
  79. plt.savefig('fig-res-8.4.pdf')
  80. plt.show()

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