绘制决策边界
示例
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
iris = datasets.load_iris()
X = iris.data
y = iris.target
X= X[y<2, :2]
y = y[y<2]
def plot_decision_boundary(clf, X,y):
"""
绘制决策边界
:param clf: 模型
:param X: 样本特征
:param y: 样本标记
"""
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
h = 0.01
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
y_predict = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
# cmap = plt.cm.Spectral 表示根据c值绘制不同颜色进行区分,也可以分别指定颜色绘制
plt.contourf(xx, yy, y_predict, cmap=plt.cm.Spectral, alpha=0.2)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
if __name__ == '__main__':
clf = LogisticRegression()
clf.fit(X, y)
# 绘图
plot_decision_boundary(clf, X, y)
plt.show()