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.

logistic_demo.py 2.4 kB

6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding=utf8 -*-
  2. from __future__ import division
  3. import numpy as np
  4. import sklearn.datasets
  5. import matplotlib.pyplot as plt
  6. np.random.seed(0)
  7. data, label = sklearn.datasets.make_moons(200, noise=0.30)
  8. def plot_decision_boundary(predict_func, data, label):
  9. """画出结果图
  10. Args:
  11. pred_func (callable): 预测函数
  12. data (numpy.ndarray): 训练数据集合
  13. label (numpy.ndarray): 训练数据标签
  14. """
  15. x_min, x_max = data[:, 0].min() - .5, data[:, 0].max() + .5
  16. y_min, y_max = data[:, 1].min() - .5, data[:, 1].max() + .5
  17. h = 0.01
  18. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
  19. Z = predict_func(np.c_[xx.ravel(), yy.ravel()])
  20. print(Z.shape)
  21. Z = Z.reshape(xx.shape)
  22. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  23. plt.scatter(data[:, 0], data[:, 1], c=label, cmap=plt.cm.Spectral)
  24. plt.show()
  25. def sigmoid(x):
  26. return 1.0 / (1 + np.exp(-x))
  27. class Logistic(object):
  28. """logistic回归模型"""
  29. def __init__(self, data, label):
  30. self.data = data
  31. self.label = label
  32. self.data_num, n = np.shape(data)
  33. self.weights = np.ones(n)
  34. self.b = 1
  35. def train(self, num_iteration=150):
  36. """随机梯度上升算法
  37. Args:
  38. data (numpy.ndarray): 训练数据集
  39. labels (numpy.ndarray): 训练标签
  40. num_iteration (int): 迭代次数
  41. """
  42. for j in range(num_iteration):
  43. data_index = range(self.data_num)
  44. for i in range(self.data_num):
  45. # 学习速率
  46. alpha = 0.01
  47. rand_index = int(np.random.uniform(0, len(data_index)))
  48. error = self.label[rand_index] - sigmoid(sum(self.data[rand_index] * self.weights + self.b))
  49. self.weights += alpha * error * self.data[rand_index]
  50. self.b += alpha * error
  51. def predict(self, predict_data):
  52. """预测函数"""
  53. result = map(lambda x: 1 if sum(self.weights * x + self.b) > 0 else 0,
  54. predict_data)
  55. print(result)
  56. return np.array(result)
  57. if __name__ == '__main__':
  58. logistic = Logistic(data, label)
  59. logistic.train(200)
  60. plot_decision_boundary(lambda x: logistic.predict(x), data, label)

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

Contributors (1)