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.3.py 2.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #尝试用逻辑回归解决
  25. x = torch.from_numpy(x).float()
  26. y = torch.from_numpy(y).float()
  27. w = nn.Parameter(torch.randn(2, 1))
  28. b = nn.Parameter(torch.zeros(1))
  29. # [w,b]是模型的参数; 1e-1是学习速率
  30. optimizer = torch.optim.SGD([w, b], 1e-1)
  31. criterion = nn.BCEWithLogitsLoss()
  32. def logistic_regression(x):
  33. return torch.mm(x, w) + b
  34. for e in range(100):
  35. # 模型正向计算
  36. out = logistic_regression(Variable(x))
  37. # 计算误差
  38. loss = criterion(out, Variable(y))
  39. # 误差反传和参数更新
  40. optimizer.zero_grad()
  41. loss.backward()
  42. optimizer.step()
  43. if (e + 1) % 20 == 0:
  44. print('epoch:{}, loss:{}'.format(e+1, loss.item()))
  45. def plot_decision_boundary(model, x, y):
  46. # Set min and max values and give it some padding
  47. x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
  48. y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
  49. h = 0.01
  50. # Generate a grid of points with distance h between them
  51. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,y_max, h))
  52. # Predict the function value for the whole grid .c_ 按行连接两个矩阵,左右相加。
  53. Z = model(np.c_[xx.ravel(), yy.ravel()])
  54. Z = Z.reshape(xx.shape)
  55. # Plot the contour and training examples
  56. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  57. plt.ylabel("x2")
  58. plt.xlabel("x1")
  59. for i in range(m):
  60. if y[i] == 0:
  61. plt.scatter(x[i, 0], x[i, 1], marker='8',c=0, s=40, cmap=plt.cm.Spectral)
  62. else:
  63. plt.scatter(x[i, 0], x[i, 1], marker='^',c=1, s=40)
  64. def plot_logistic(x):
  65. x = Variable(torch.from_numpy(x).float())
  66. out = F.sigmoid(logistic_regression(x))
  67. out = (out > 0.5) * 1
  68. return out.data.numpy()
  69. plot_decision_boundary(lambda x: plot_logistic(x), x.numpy(), y.numpy())
  70. plt.title('逻辑回归')
  71. plt.savefig('fig-res-8.3.pdf')
  72. plt.show()

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