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.

ann_classification.py 4.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. __author__ = 'm.bashari'
  2. import numpy as np
  3. from sklearn import datasets, linear_model
  4. import matplotlib.pyplot as plt
  5. class Config:
  6. nn_input_dim = 2 # input layer dimensionality
  7. nn_output_dim = 2 # output layer dimensionality
  8. # Gradient descent parameters (I picked these by hand)
  9. epsilon = 0.01 # learning rate for gradient descent
  10. reg_lambda = 0.01 # regularization strength
  11. def generate_data():
  12. np.random.seed(0)
  13. X, y = datasets.make_moons(200, noise=0.20)
  14. return X, y
  15. def visualize(X, y, model):
  16. # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)
  17. # plt.show()
  18. plot_decision_boundary(lambda x:predict(model,x), X, y)
  19. plt.title("Logistic Regression")
  20. def plot_decision_boundary(pred_func, X, y):
  21. # Set min and max values and give it some padding
  22. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
  23. y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
  24. h = 0.01
  25. # Generate a grid of points with distance h between them
  26. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
  27. # Predict the function value for the whole gid
  28. Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
  29. Z = Z.reshape(xx.shape)
  30. # Plot the contour and training examples
  31. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  32. plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
  33. plt.show()
  34. # Helper function to evaluate the total loss on the dataset
  35. def calculate_loss(model, X, y):
  36. num_examples = len(X) # training set size
  37. W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2']
  38. # Forward propagation to calculate our predictions
  39. z1 = X.dot(W1) + b1
  40. a1 = np.tanh(z1)
  41. z2 = a1.dot(W2) + b2
  42. exp_scores = np.exp(z2)
  43. probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
  44. # Calculating the loss
  45. corect_logprobs = -np.log(probs[range(num_examples), y])
  46. data_loss = np.sum(corect_logprobs)
  47. # Add regulatization term to loss (optional)
  48. data_loss += Config.reg_lambda / 2 * (np.sum(np.square(W1)) + np.sum(np.square(W2)))
  49. return 1. / num_examples * data_loss
  50. def predict(model, x):
  51. W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2']
  52. # Forward propagation
  53. z1 = x.dot(W1) + b1
  54. a1 = np.tanh(z1)
  55. z2 = a1.dot(W2) + b2
  56. exp_scores = np.exp(z2)
  57. probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
  58. return np.argmax(probs, axis=1)
  59. # This function learns parameters for the neural network and returns the model.
  60. # - nn_hdim: Number of nodes in the hidden layer
  61. # - num_passes: Number of passes through the training data for gradient descent
  62. # - print_loss: If True, print the loss every 1000 iterations
  63. def build_model(X, y, nn_hdim, num_passes=20000, print_loss=False):
  64. # Initialize the parameters to random values. We need to learn these.
  65. num_examples = len(X)
  66. np.random.seed(0)
  67. W1 = np.random.randn(Config.nn_input_dim, nn_hdim) / np.sqrt(Config.nn_input_dim)
  68. b1 = np.zeros((1, nn_hdim))
  69. W2 = np.random.randn(nn_hdim, Config.nn_output_dim) / np.sqrt(nn_hdim)
  70. b2 = np.zeros((1, Config.nn_output_dim))
  71. # This is what we return at the end
  72. model = {}
  73. # Gradient descent. For each batch...
  74. for i in range(0, num_passes):
  75. # Forward propagation
  76. z1 = X.dot(W1) + b1
  77. a1 = np.tanh(z1)
  78. z2 = a1.dot(W2) + b2
  79. exp_scores = np.exp(z2)
  80. probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
  81. # Backpropagation
  82. delta3 = probs
  83. delta3[range(num_examples), y] -= 1
  84. dW2 = (a1.T).dot(delta3)
  85. db2 = np.sum(delta3, axis=0, keepdims=True)
  86. delta2 = delta3.dot(W2.T) * (1 - np.power(a1, 2))
  87. dW1 = np.dot(X.T, delta2)
  88. db1 = np.sum(delta2, axis=0)
  89. # Add regularization terms (b1 and b2 don't have regularization terms)
  90. dW2 += Config.reg_lambda * W2
  91. dW1 += Config.reg_lambda * W1
  92. # Gradient descent parameter update
  93. W1 += -Config.epsilon * dW1
  94. b1 += -Config.epsilon * db1
  95. W2 += -Config.epsilon * dW2
  96. b2 += -Config.epsilon * db2
  97. # Assign new parameters to the model
  98. model = {'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2}
  99. # Optionally print the loss.
  100. # This is expensive because it uses the whole dataset, so we don't want to do it too often.
  101. if print_loss and i % 1000 == 0:
  102. print("Loss after iteration %i: %f" % (i, calculate_loss(model, X, y)))
  103. return model
  104. def classify(X, y):
  105. # clf = linear_model.LogisticRegressionCV()
  106. # clf.fit(X, y)
  107. # return clf
  108. pass
  109. def main():
  110. X, y = generate_data()
  111. model = build_model(X, y, 3, print_loss=True)
  112. visualize(X, y, model)
  113. if __name__ == "__main__":
  114. main()

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