机器学习 绘制决策边界

两个特征的决策边界绘制。

1.数据处理

1.1 数据准备

使用 Iris 鸢尾花数据集,进行分析可视化。平面图只能绘制两个特征,这里我们也取数据集中的两列特征。

# 引入数据
from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
# 'feature_names': ['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width(cm)'],
#只取其中两个特征 第三列和第四列,[0,3]则代表取第一列和第四列
X = iris.data[:,[2,3]]  
y = iris.target
print("Class labels:",np.unique(y))  #打印分类类别的种类

1.2 数据集切分

# 切分训练数据和测试数据
from sklearn.model_selection import train_test_split
## 30%测试数据,70%训练数据,stratify=y表示训练数据和测试数据具有相同的类别比例
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1,stratify=y)

train_test_split函数中stratify=y的理解:

kind,count=np.unique(y_train,return_counts=True)
print(count)
kind_test,count_test=np.unique(y_test,return_counts=True)
print(count_test)
'''
输出结果:
[35 35 35]
[15 15 15]
'''

1.3 数据标准化

注意标准化本质上是一种线性变换,它并没有改变一个数据在该组数据中的位置,也没有改变该组数据分布的形状,而只是将该组数据变成平均值为0、标准差为1
在这里插入图片描述

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
## 估算训练数据中的mu和sigma
sc.fit(X_train)
## 使用训练数据中的mu和sigma对数据进行标准化
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

2.绘制决策边界

2.1 可视化函数(两个特征)

# 画出决策边界图(只有在2个特征才能画出来)
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.colors import ListedColormap

def plot_decision_region(X,y,classifier,resolution=0.02):
    markers = ('s','x','o','^','v')
    colors = ('red','blue','lightgreen','gray','cyan')
    # 背景色
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    #这里+1  -1的操作我理解为防止样本落在图的边缘处,不知道对不对
    x1_min,x1_max = X[:,0].min()-1,X[:,0].max()+1
    #print(x1_min, x1_max)
    
    x2_min,x2_max = X[:,1].min()-1,X[:,1].max()+1
    #print(x2_min, x2_max)

    # 生成网格点坐标矩阵
    xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,resolution),
                         np.arange(x2_min,x2_max,resolution))  
    Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    # 绘制轮廓等高线  alpha参数为透明度
    plt.contourf(xx1,xx2,Z,alpha=0.3,cmap=cmap)
    plt.xlim(xx1.min(),xx1.max())
    plt.ylim(xx2.min(),xx2.max())

    # plot class samples
    for idx,cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y==cl,0],
                   y = X[y==cl,1],
                   alpha=0.8,
                   c=colors[idx],
                   marker = markers[idx],
                   label=cl,
                   edgecolors='black')

2.2 决策树模型

## 决策树分类器  标准化之后的数据
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion='gini',max_depth=4,random_state=1)
tree.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=tree,resolution=0.01)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()
# tree.score(X_test_std, y_test) # 0.98

在这里插入图片描述

## 决策树分类器  原始数据
tree_1 = DecisionTreeClassifier(criterion='gini',max_depth=4,random_state=1)
tree_1.fit(X_train,y_train)
plot_decision_region(X_train,y_train,classifier=tree_1,resolution=0.01)
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc='upper left')
plt.show()
# tree_1.score(X_test, y_test) # 0.98

在这里插入图片描述

2.3 KNN模型

## 使用KNN分类器  标准化之后的数据
from sklearn.neighbors import KNeighborsClassifier

knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train_std,y_train)
plot_decision_region(X_train_std,y_train,classifier=knn,resolution=0.02)
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.show()
# knn.score(X_test_std, y_test)  # 测试集得分 1.0

在这里插入图片描述

## KNN分类器  原始数据
knn_1 = KNeighborsClassifier(n_neighbors=3)
knn_1.fit(X_train,y_train)
plot_decision_region(X_train,y_train,classifier=knn_1,resolution=0.02)
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc='upper left')
plt.show()
# knn_1.score(X_test, y_test)  # 测试集得分 0.98

在这里插入图片描述

3. 参考链接

1、机器学习之sklearn基础教程!
2、Plot the decision boundaries of a VotingClassifier

  • 5
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值