机器学习算法-KNN

·KNN算法的基本过程:

1)计算测试数据与各个训练数据之间的距离
2)按照距离的递增关系进行排序
3)选取距离最小的K个点
4)确定前K个点所在类别的出现频率
5)返回前K个点中出现频率最高的类别作为测试数据的预测分类

·算法的优缺点

优点:精度高、对异常值不敏
缺点:计算复杂度高、空间复杂度高

基本实现流程:

# 导入包
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np

# 加载数据集
iris = load_iris()
# 数据集的划分
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=666, test_size=0.2)
# 设置邻居数,即n_neighbors的大小
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(x_train, y_train)

y_pre = knn.predict(x_test)
# print(y_pre=y_test)
print("准确率为:\n", knn.score(x_test, y_pre))

·手撕KNN代码,刨析KNN原理

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from sklearn.datasets import load_iris

# %matplotlib inline

iris = load_iris()  # 加载数据
X = iris.data[:, (1, 3)]  # 为方便画图,仅采用数据的其中两个特征
y = iris.target

cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

# 决策边界,用不同颜色表示
x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1
y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
                     np.arange(y_min, y_max, 0.02))


def knn_code(loc, k=5, order=2 ):  # k order是超参
    # print(order)
    diff_loc = X - loc
    dis_loc = np.linalg.norm(diff_loc, ord=order, axis=1) # 没有axis得到一个数,矩阵的泛数。axis=0,得到两个数
    knn = y[dis_loc.argsort()[:k]]
    counts = np.bincount(knn)
    return np.argmax(counts)


line_loc = np.array(list(zip(xx.ravel(), yy.ravel())))

plt.figure(figsize=(15, 12))  # 图的尺寸

pos = 1  # 位置计数器

for k in [2, 6]:
    for order in [1, 2]:
        Z = np.array([knn_code(ii, k, order) for ii in line_loc]).reshape(xx.shape)  # 这个是不支持向量化运算的
        ax = plt.subplot(220 + pos)  # 几行,几列,第几个,先按行数
        ax.pcolormesh(xx, yy, Z, cmap=cmap_light, shading='auto')  # 绘制预测结果图
        ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)  # 补充训练数据点
        ax.set_title(f'k: {k}, distance order: {order}')
        pos += 1

plt.suptitle('I am a tuner!')
plt.show()

KNN实现鸢尾花可视化

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值