8-2-LogisticRegression-demo.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from sklearn.datasets import load_iris
  2. from sklearn.linear_model import LogisticRegression
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. def main():
  6. # 加载数据集,只加载两个特征
  7. iris = load_iris()
  8. x = iris.data[:, :2]
  9. y = iris.target
  10. h = .02
  11. # 逻辑回归训练并预测
  12. lr = LogisticRegression(C=1e5)
  13. lr.fit(x, y)
  14. # 返回坐标矩阵
  15. x_min, x_max = x[:, 0].min() - .5, x[:, 0].max() + .5
  16. y_min, y_max = x[:, 1].min() - .5, x[:, 1].max() + .5
  17. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
  18. Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])
  19. # 结果可视化
  20. Z = Z.reshape(xx.shape)
  21. plt.figure(1, figsize=(4, 3))
  22. plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
  23. plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', cmap=plt.cm.Paired)
  24. plt.xlabel('Sepal length')
  25. plt.ylabel('Sepal width')
  26. plt.xlim(xx.min(), xx.max())
  27. plt.ylim(yy.min(), yy.max())
  28. plt.xticks(())
  29. plt.yticks(())
  30. plt.show()
  31. if __name__ == "__main__":
  32. main()