pythonK-NN算法是什么?
python中K-NN算法是什么?
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
KNearestNeighbor算法⼜叫KNN算法,这个算法是机器学习⾥⾯⼀个⽐较经典的算法,总体来说KNN算法是相对⽐
较容易理解的算法。
1、定义
如果⼀个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某⼀个类别,则该样本也属于这个类别。(起源:KNN最早是由Cover和Hart提出的一种分类算法);俗话就是:根据“邻居”来推断出你的类别。
2、基本流程
(1)计算已知类数据集中的点与当前点之间的距离2)按距离递增次序排序
(2)选取与当前点距离最小的k个点
(3)统计前k个点所在的类别出现的频率
(4)返回前k个点出现频率最高的类别作为当前点的预测分类
3、实例
代码涉及sklean库,需要安装sklearn库。
fromsklearn.datasetsimportload_iris
fromsklearn.model_selectionimporttrain_test_split
fromsklearn.preprocessingimportStandardScaler
fromsklearn.neighborsimportKNeighborsClassifier
#1.获取数据
iris=load_iris()
#2.数据基本处理:训练集的特征值x_train测试集的特征值x_test训练集的⽬标值y_train测试集的⽬标值y_test,
'''
x:数据集的特征值
y:数据集的标签值
test_size:测试集的⼤⼩,⼀般为float
random_state:随机数种⼦,不同的种⼦会造成不同的随机采样结果。相同的种⼦采样结果相同
'''
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.2,random_state=22)
#3.特征工程-特征预处理
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)
#4.机器学习-KNN
#4.1实例化一个估计器
estimator=KNeighborsClassifier(n_neighbors=5)
#4.2模型训练
estimator.fit(x_train,y_train)
#5.模型评估
#5.1预测值结果输出
y_pre=estimator.predict(x_test)
print("预测值是:\n",y_pre)
print("预测值和真实值的对比是:\n",y_pre==y_test)
#5.2准确率计算
score=estimator.score(x_test,y_test)
print("准确率为:\n",score)
以上就是python中K-NN算法的介绍,希望能对大家有所帮助。更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python中ndarray与list转换的方法
python中ndarray与list转换的方法在python数据类型中,list元素可以任意类型组合,而ndarray元素类型必须相同,但是ndarray可以更方便的对多维...详情>>
2023-11-10 08:51:14
python中OrdereDict如何使用?
python中OrdereDict如何使用?我们在对数据进行处理时,如果能够使它们保存顺序的排序,那么用起来会非常的便利。不过字典本身就是没有顺序的,...详情>>
2023-11-10 07:05:00
python中如何使用scipy.fftpack模块计算快速傅里叶变换?
python中如何使用scipy.fftpack模块计算快速傅里叶变换?在编程中,快速傅里叶变换是工程中非常有价值的一类算法,它可以将时域和频域的信号相互...详情>>
2023-11-10 05:50:23
zip()函数如何在python中遍历多个列表?
zip()函数如何在python中遍历多个列表?下面我们就python中zip的说明、语法、使用注意点进行讲解,然后带来遍历多个列表的实例。1、说明zip()函...详情>>
2023-11-10 05:38:33热门推荐
python concat函数有何用法?
沸python里函数装饰器怎么使用?
热如何实现python中的continue语句?
热python中的冒泡排序是什么?
新python中str函数是什么
如何使用python实现项目进度显示?
python中ndarray与list转换的方法
python复制文件的方法整理
Python中numpy数组如何添加元素
python有几种可视化图形库?
python中xlwings是什么?
python上下文管理器的基本介绍
Python自动化测试基础必备知识点一
python中OrdereDict如何使用?
技术干货






