02-19 k近邻算法(鸢尾花分类)

k近邻算法(鸢尾花分类)

导入模块

1554348418590

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.font_manager import FontProperties
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

获取数据

iris_data = datasets.load_iris()
X = iris_data.data[:, [2, 3]]
y = iris_data.target
label_list = ['山鸢尾', '杂色鸢尾', '维吉尼亚鸢尾']

构建决策边界

def plot_decision_regions(X, y, classifier):
    # 构造颜色映射关系
    marker_list = ['o', 'x', 's']
    color_list = ['r', 'b', 'g']
    cmap = ListedColormap(color_list[:len(np.unique(y))])

    # 构造网格采样点并使用算法训练阵列中每个元素
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1  # 第0列的范围
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1  # 第1列的范围
    t1 = np.linspace(x1_min, x1_max, 666)  # 横轴采样多少个点
    t2 = np.linspace(x2_min, x2_max, 666)  # 纵轴采样多少个点

    x1, x2 = np.meshgrid(t1, t2)  # 生成网格采样点
    y_hat = classifier.predict(np.array([x1.ravel(), x2.ravel()]).T)  # 预测值
    y_hat = y_hat.reshape(x1.shape)  # 使之与输入的形状相同
    # 通过网格采样点画出等高线图
    plt.contourf(x1, x2, y_hat, alpha=0.2, cmap=cmap)
    plt.xlim(x1.min(), x1.max())
    plt.ylim(x2.min(), x2.max())

    for ind, clas in enumerate(np.unique(y)):
        plt.scatter(X[y == clas, 0], X[y == clas, 1], alpha=0.8, s=50,
                    c=color_list[ind], marker=marker_list[ind], label=label_list[clas])

训练模型

knn = KNeighborsClassifier(n_neighbors=10, p=2)  # p=2为欧几里得距离;p=1为曼哈顿距离
knn.fit(X, y)
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=None, n_neighbors=10, p=2,
           weights='uniform')

1554348418590

构图

plot_decision_regions(X, y, classifier=knn)
plt.xlabel('花瓣长度(cm)', fontproperties=font)
plt.ylabel('花瓣宽度(cm)', fontproperties=font)
plt.legend(prop=font)
plt.show()

posted @ 2019-10-14 13:27  小猿取经-林海峰老师  阅读(739)  评论(0编辑  收藏  举报